我有一个 Button
对象和一个 Imagebutton
对象。我想要做的就是为它们分配相同的背景颜色。
但是图像按钮的背景颜色似乎总是比“普通”按钮的颜色更亮?!在模拟器上稍微亮一点,在我的 S3 Mini 上更亮。 为什么?
private final int BUTTON_BACKGROUND_COLOR_CODE = Color.LTGRAY;
...
RelativeLayout TopLayout = (RelativeLayout) findViewById(R.id.topLayout);
TopLayout.removeAllViews();
TopLayout.setPadding(m_TableRowLeftPadding_px, 8, m_TableRowRightPadding_px, 4);
RelativeLayout.LayoutParams bParams = new RelativeLayout.LayoutParams(m_DefaultButtonWidth_px,
m_CurrentButtonHeight_px);
bParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
bParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
Button itemAddButton = new Button(this);
itemAddButton.getBackground().setColorFilter(BUTTON_BACKGROUND_COLOR_CODE,
PorterDuff.Mode.SRC_IN);
itemAddButton.setLayoutParams(bParams);
itemAddButton.setText(m_Resources.getString(R.string.AddItemButtonString));
itemAddButton.setId(ADD_ITEM_BUTTON_ID);
itemAddButton.setOnClickListener(new View.OnClickListener()
{
...
});
TopLayout.addView(itemAddButton);
RelativeLayout.LayoutParams ibParams = new RelativeLayout.LayoutParams(MIN_IMG_BUTTON_WIDTH,
m_CurrentButtonHeight_px);
ibParams.addRule(RelativeLayout.LEFT_OF, itemAddButton.getId());
ImageButton speechButton = new ImageButton(this);
speechButton.setLayoutParams(ibParams);
// speechButton.setImageDrawable(m_Resources.getDrawable(R.drawable.micro2));
speechButton.setContentDescription(m_Resources.getString(R.string.AddSpeechItemString));
speechButton.getBackground().setColorFilter(BUTTON_BACKGROUND_COLOR_CODE,
PorterDuff.Mode.SRC_IN);
speechButton.setOnClickListener(new View.OnClickListener()
{
...
});
TopLayout.addView(speechButton);
最佳答案
@ChristianGraf 移除滤色器并检查 ImageButton 和 Button 的原始背景:它们的亮度应该不同。这意味着背景本来就不同。
我们如何解决这个问题?我们不可以;很简单,因为系统用作 ImageButton 和 Button 背景的可绘制对象的亮度不同。如果您在更多设备上尝试代码,您可能会注意到更多/其他/更少的差异。
一种解决方案是设置 PorterDuff.Mode
在setColorFilter
到 SRC 或 DST。这实际上会改变预期的结果。
解决方案(使用其中一个背景两次)
在您的代码中,您首先修复了 itemAddButton
的背景(按钮)使用这一行:
itemAddButton.getBackground().setColorFilter(BUTTON_BACKGROUND_COLOR_CODE,
PorterDuff.Mode.SRC_IN);
稍后,您使用相同的代码来设置修复 speechButton
的背景(图像按钮):
<罢工>罢工>
speechButton.getBackground().setColorFilter(BUTTON_BACKGROUND_COLOR_CODE,
PorterDuff.Mode.SRC_IN);
罢工><罢工>罢工> 现在,您所要做的就是不设置背景的滤色器,让我们使用您的第一个 View (按钮)的背景:
speechButton.setBackgroundDrawable(itemAddButton.getBackground());
这将确保他们具有相同的背景。
关于android - 为按钮和图像按钮设置相同的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16031694/