How to create button in Android Behind code?

Asked

Viewed 339 times

4

I’m developing an app where I download some images from the internet when the app opens.

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

With the answer Icero worked, I’m only with a problem the image got bigger than the screen and is being cut, have I decrease it within the code or just treat it before putting in the code?

1 answer

5


You can do both in XML and via code.

The advantage of being via XML is that you don’t write as 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 is null above, you can pass the father, who will be the 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);
  • thanks I’ll try.

  • Cicero my project gave an error like this : Default Activity not found, but I only have one Activity and it has no error.

  • @Ilgneroliveira made the reference of Activity no Manifest.xml ?

  • yes. nor did I touch <Activity android:name=". Myactivity" android:label="@string/app_name" > <Intent-filter> <action android:name="android.intent.action.MAIN" /> <Category android:name="android.intent.Category.LAUNCHER" /> </Intent-filter> </Activity>

  • This is because there is some error in your project. See if next to Run up there in the IDE, the Android doll where your project’s name is with red X error. This error you saw occurs when there is an error in the project or even in the manifest, as @Antony Alkimim mentioned above.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.