Android How to programmatically change the width of my ImageButton?

I have an ImageButton. The code -

ImageButton shareButton = new ImageButton(this);
shareButton.setBackgroundResource(android.R.drawable.ic_menu_share);

RelativeLayout.LayoutParams shareParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
shareParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, navigationLogo.getId());

shareButton.setLayoutParams(shareParams);

I need to change its width. But there is no setWidth method in both ImageButton and layout options. Looked a lot online with no response.

+3
source share
2 answers

Instead of using RelativeLayout.WRAP_CONTENT for the width, you can use the actual number, which will be the new button width in pixels. Since you probably want the width in dp to be resolution independent, you probably need to convert dp to pixels using the following method:

public static int dpToPixels(Context context, float dp) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dp * scale + 0.5f);
}
+8
source

Try it.

ImageButton shareButton = new ImageButton(this);
shareButton.setBackgroundResource(android.R.drawable.ic_menu_share);

RelativeLayout.LayoutParams shareParams = new RelativeLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
shareParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, navigationLogo.getId());
shareParams.width = INTEGER_NUMBER;
shareButton.setLayoutParams(shareParams);
0
source

All Articles