如何在android中设置更大的背景图像时设置ImageButton的宽度?

时间:2012-08-23 05:46:13

标签: android width imagebutton

我想在Android中将较大的Image设置为ImageButton的背景,并将其高度和宽度设置为固定。我能够创建图像按钮,如下所示。但是Image的尺寸越来越大。如何根据按钮的大小来确定其大小。

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

提前致谢

3 个答案:

答案 0 :(得分:1)

您可以尝试:

b0.setScaleType(ScaleType.FIT_XY);

希望有所帮助

答案 1 :(得分:1)

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

public void setImageBitmap (Bitmap bm)

public void setImageDrawable (Drawable drawable)

public void setImageResource (int resId)

答案 2 :(得分:0)

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

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