Search code examples
androidimagebuttonandroid-imagebutton

Add an ImageButton programmatically with a Chosen Size


I'm on Android Studio, and I would like to create an ImageButton in my code. The problem is, when I create it, I don't know how to set its size (It's too big).

I proceed like this: I have a linear layout created with xml (added) where i put I put a RelativeLayout which contains a TextView and my ImageButton. I set the params when I put my IB in the layout. Here is the code:

final RelativeLayout rl = new RelativeLayout(Selection.this);
final TextView someone = new TextView(Selection.this);
final ImageButton cross = new ImageButton(Selection.this);

RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);

cross.setBackgroundResource(R.drawable.stop);

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( 
   RelativeLayout.LayoutParams.WRAP_CONTENT, 
   RelativeLayout.LayoutParams.WRAP_CONTENT);

cross.setLayoutParams(lp);
cross.setScaleType(ImageView.ScaleType.FIT_XY);

someone.setText(et.getText());

rl.addView(someone);
rl.addView(cross);
added.addView(rl,rlp);

Solution

  • The parameters the ImageButton gets are those of lp which you set with width and height RelativeLayout.LayoutParams.WRAP_CONTENT , therefore the ImageButton will use the size of the image which might be too big for you. Try choosing a specific size :

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( 
    60,60);
    

    or add the ImageButton view inside another layout that you already constrained its sizes.