Android - 如何以编程方式更改ImageButton的宽度?

Suc*_*chi 3 android width imagebutton

我有一个ImageButton.代码是 -

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);
Run Code Online (Sandbox Code Playgroud)

我需要改变它的宽度.但是ImageButton和布局参数都没有setWidth方法.在没有答案的情况下在网上看了很多.

Mic*_*ine 8

您可以使用实际数字,而不是使用RelativeLayout.WRAP_CONTENT作为宽度,该数字将是按钮的新宽度(以像素为单位).由于您可能希望将dp中的宽度指定为与分辨率无关,因此您可能需要使用如下方法将dp转换为像素:

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