开发者

Android - How do I change the width of my ImageButton programmatically?

I have an ImageButton开发者_如何学JAVA. The code is -

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 as well as the layout params. Looked a lot online without an answer.


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

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


Try this.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜