【问题标题】:How to set width of ImageButton when setting the background image larger in android?在android中设置更大的背景图像时如何设置ImageButton的宽度?
【发布时间】:2012-08-23 05:46:12
【问题描述】:

我想以编程方式将较大的图像设置为 Android 中 ImageButton 的背景,并将其高度和宽度设置为固定值。我可以按如下方式创建图像按钮。但是图像的大小越大。如何根据按钮的大小固定其大小。

ImageButton b0=new ImageButton(this);
b0.setMaxWidth(100);
b0.setMinimumWidth(100);
b0.setMaxHeight(80);
b0.setBackgroundResource(R.drawable.tattoo0);
tattooListView.addView(b0);

提前致谢

【问题讨论】:

    标签: android width imagebutton


    【解决方案1】:

    你可以试试:

    b0.setScaleType(ScaleType.FIT_XY);
    

    希望对你有帮助

    【讨论】:

    • OK,那你可以试试用setBackgroungDrawable()代替setBackgroundResource()
    • 只需更改 b0.setBackgroundResource(R.drawable.tattoo0); for b0.setBackgroundDrawable(R.drawable.tattoo0);
    【解决方案2】:

    ScaleType 不适用于背景,它适用于源图像。您可以通过 xml 中的 src 属性设置源图像,也可以通过 setImage() 方法以编程方式设置,如下所示:

    public void setImageBitmap (Bitmap bm)

    public void setImageDrawable (Drawable drawable)

    public void setImageResource (int resId)

    【讨论】:

    • 如何使用 setimage() 设置按钮的背景图片?
    【解决方案3】:

    这段代码帮助我实现了我的目标。

         ImageButton btn = new ImageButton(getApplicationContext());
         String str=String.format("drawable/theimage");
        int imageResource = getResources().getIdentifier(str, null, getPackageName());
    
        BitmapDrawable drawable = (BitmapDrawable)getApplicationContext().getResources().getDrawable(imageResource);
                Bitmap bitmap = drawable.getBitmap();
                bitmap = Bitmap.createScaledBitmap(bitmap, 100, 80, true); 
    
                btn.setBackgroundColor(80000000);
                btn.setImageBitmap(bitmap);
    
    
                btn.setTag(1);
    
                linearlayoutview.addView(btn);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多