3

我需要一个带有前景透明图像和背景颜色的按钮。所以有使用这个代码。背景颜色在图像之外。我需要与图像大小相同的按钮。

根据用户交互,我必须更改前景图像和背景颜色。我想分别添加图像和背景颜色,以便我可以以最低成本更改其中一个。我必须在这个 UI 中使用很多按钮,所以它将在 java 代码中完成。

layout = new TableLayout(this);
layout.setLayoutParams(new TableLayout.LayoutParams(8,7));
TableRow row2 = new TableRow(this);
buttonPlayer1 = new ImageButton(this);
buttonPlayer1.setImageDrawable(getResources().getDrawable(R.drawable.blankc4));
buttonPlayer1.setBackgroundColor(Color.GREEN);
row2.addView(buttonPlayer1);
layout.addView(row2);
4

1 回答 1

1

如果您唯一的问题是按钮背景颜色变得过大图像并且您需要按钮大小与图像大小相同,则使用图像对象上的 & 方法获取图像高度 和宽度使用这些值使按钮大小与使用图像大小相同&方法分别在按钮对象上。getHeight()getWidth()setHeight()setWidth()

带有 LinearLayout 的示例代码:


 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout btnLO = new LinearLayout(this);    
        btnLO.setOrientation(LinearLayout.VERTICAL);
        ImageButton i1 = new ImageButton(this);
        i1.setBackgroundColor(color.background_dark);
        i1.setImageDrawable(getResources().getDrawable(R.drawable.rana));   
        btnLO.addView(i1, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));                      
  //    btnLO.setGravity(Gravity.LEFT | Gravity.CENTER_HORIZONTAL);     
        this.addContentView(btnLO, new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); 
    }
于 2012-05-20T20:04:16.290 回答