Android按钮使用透明PNG图像和背景颜色

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

如果您想在不同的状态下更改按钮的行为(如点击、聚焦、正常),请尝试使用选择器。 - K_Anas
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)); 
    }

我也尝试了setHeight()和setWidth()方法,但是ImageButton没有这样的方法。我还尝试了setMaxHeight()和setMaxWidth()方法,但是它们并没有给出正确的输出。 - Sudeepta
@Sudeepta 我有解决方案,使用row2.addView(buttonPlayer1,new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));代替row2.addView(buttonPlayer1);,然后你的imagebutton将采用给定图像的大小。这将解决你的问题。你也可以手动定义imagebutton的大小,例如row2.addView(buttonPlayer1,new LayoutParams(300,300));。最后,你应该检查setMinimumHeight和setWidth方法 :) - Imran Rana
我已经测试过了,但是当我使用LayoutParams.FILL_PARENT或者LayoutParams(100, 100)时,它什么也不显示。另一个惊人的事情是,当我在setMinimumHeight和setWidth之后使用row2.addView(buttonPlayer1); getHeight()和width返回0,但在按钮操作中它返回100和103。 - Sudeepta
听起来很有趣,我通过将imagebutton添加到LinearLayout中进行了检查(您可以从我的编辑答案中检查它)。为什么layout有像8、7这样的参数,您是如何附加它们的? - Imran Rana
在主代码布局中,参数将为8,7。对于LinearLayout,我以前已经了解过。如果我在UI中使用XML,则在表格布局中它的工作方式非常有趣。 - Sudeepta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接