2013-04-16 106 views
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); 
+0

为什么不使用两个'Buttons'或两个'ImageButtons'而不是一个'Button'和'ImageButton' ?? – Renjith

+0

“为什么我的S3 Mini在模拟器上亮了一点,路明亮了?”这取决于设备的屏幕规格。您会在另一款智能手机上看到另一种颜色的亮度。 – JJ86

+0

@RKN:ImageButton不允许设置文本,字体等。而“普通”按钮不允许添加图像,这是我的意图。我只是评论一下,以避免我的图像的“透明”背景造成的视觉干扰。 –

回答

1

@ChristianGraf移除滤镜并检查ImageButton和Button的原始背景:它们应该有不同的亮度。这意味着背景本来是不同的。


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


一种解决方案可以是在setColorFilterPorterDuff.Mode设置为SRC或DST。这实际上会改变预期的结果。


解决方案(的背景使用一个两次

在代码中,你第一次使用这条线修复的itemAddButton(按钮)backgrouond:

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

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