How to create button in Android's behind code?

4

I'm developing an application where I download some images from the internet when the application is opened.

I want, when I have these images downloaded, create a button for each image and put it in the background. But since I do not know how many images I'm going to download, I can not create the buttons in XML. I wanted to create it in java. How do I do this?

With cicero's answer worked, I'm just having a problem the image got bigger than the screen and it's being cropped, how can I reduce it inside the code or just deal with it before putting it in the code?

    
asked by anonymous 18.12.2014 / 20:09

1 answer

5

You can do both forms, both in XML and via code.

The advantage of being via XML is that you do not write so much in the code.

ImageButton:

ImageButton imageButton = new ImageButton(this);
    imageButton.setBackgroundColor(getResources().getColor(android.R.color.transparent));

    File file = new File("caminho para a imagem");
    Bitmap bmImg = BitmapFactory.decodeFile(file.getPath());
    imageButton.setImageBitmap(bmImg);

    //Se quiser algum tamanho especifico
    ViewGroup.LayoutParams layoutParams = new ActionBar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    imageButton.setLayoutParams(layoutParams);

        //aí você adiciona essa imagem onde quiser, num ViewGroup
        layoutPai.addView(imageButton);

Via XLM:

Imagebutton.xml file

<?xml version="1.0" encoding="utf-8"?>
<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:id="@+id/imageButton" />

In the code:

 ImageButton imageButton = (ImageButton)LayoutInflater.from(this).inflate(R.layout.imagebutton, null);

where it is null above, you can pass the parent, which will be ViewGroup

File file = new File("caminho para a imagem");
Bitmap bmImg = BitmapFactory.decodeFile(file.getPath());
imageButton.setImageBitmap(bmImg);

//aí você adiciona essa imagem onde quiser, num ViewGroup
layoutPai.addView(imageButton);
    
18.12.2014 / 20:31