1

I've been trying to create ImageButtons through Java but idk how, I can only do it on the xml activity screen. Basically, I want a new ImageButton to appear every second in a random place, and each ImageButton disappears when clicked. Any idea how to do that on Java? Thanks. (p.s. it's for an android app).

I know I have to import android.widget.ImageButton;

2 Answers2

0

try this:

First: find the viewgroup where you want to add the IB.

for instance:

LinearLayout layout = (LinearLayout) findViewById(R.id.mainlayout);

Second: Create and parametrize the IB

ImageButton ib = new ImageButton(this); //<-- this is the activity
ib.setImageResource(R.drawable.my_button_image);
ib.setLayoutParams(new LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));

Third: add the IB to the previous found viewgroup.

layout.addView(ib);
rnrneverdies
  • 15,243
  • 9
  • 65
  • 95
0
ImageButton button = new ImageButton(Context context);

The context object can be your activity, in which case you should pass "this" as the parameter(without the quotes). Now to make it appear on the screen you should set its layout params like this

LayoutParams params = new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
button.setLayoutParams(params);

Now you need to add the button to the screen, you need to add it to your main layout so you will have something like this

yourLayoutName.addView(button);