【问题标题】:Android - How do I change the width of my ImageButton programmatically?Android - 如何以编程方式更改 ImageButton 的宽度?
【发布时间】:2011-08-31 10:25:27
【问题描述】:

我有一个 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);

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

【问题讨论】:

    标签: android width imagebutton


    【解决方案1】:

    除了使用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);
    }
    

    【讨论】:

      【解决方案2】:

      试试这个。

      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);
      

      【讨论】:

        猜你喜欢
        • 2011-10-08
        • 1970-01-01
        • 1970-01-01
        • 2013-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多