1

我有一个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);
4

1 回答 1

1

@ChristianGraf 删除颜色过滤器并检查 ImageButton 和 Button 的原始背景:它们的亮度应该不同。这意味着背景最初是不同的。


我们如何解决这个问题?我们不可以; 很简单,因为系统用作 ImageButton 和 Button 背景的可绘制对象的亮度不同。如果您在更多设备上尝试代码,您可能会注意到更多/其他/更少的差异。


一种解决方案可能是将 设置PorterDuff.ModesetColorFilterSRC 或 DST。这实际上会改变预期的结果。


解决方案使用其中一个背景两次

在您的代码中,您首先使用以下行修复itemAddButton(Button) 的背景:

itemAddButton.getBackground().setColorFilter(BUTTON_BACKGROUND_COLOR_CODE,
PorterDuff.Mode.SRC_IN);

稍后,您使用相同的代码来设置固定speechButton(ImageButton) 的背景:

speechButton.getBackground().setColorFilter(BUTTON_BACKGROUND_COLOR_CODE,
PorterDuff.Mode.SRC_IN);

现在,您所要做的就是代替设置背景的颜色过滤器,让我们使用您的第一个视图(按钮)的背景:

speechButton.setBackgroundDrawable(itemAddButton.getBackground());

这将确保他们具有相同的背景。

于 2013-04-19T07:58:27.410 回答