我创建了一个View
并希望在选择它时出现涟漪效果。我使用?attr/selectableItemBackground
实现了这一点。但是,我还想在选择该View
时设置其背景颜色。我尝试使用setBackgroundResource(selectableAttr)
然后使用setBackgroundColor(colorSelectBackground)
,但是颜色好像覆盖了资源,所以我只有其中之一。以下是我的代码:
int[] attrs = new int[]{R.attr.selectableItemBackground};
TypedArray typedArray = context.obtainStyledAttributes(attrs);
int backRes = typedArray.getResourceId(0, 0);
public void select() {
view.setSelected(true);
view.setBackgroundResource(backRes);
view.setBackground(colorSelectBackground);
}
public void deselect() {
view.setSelected(false);
view.setBackground(colorSelectBackground);
}
有人知道如何同时使用
?attr/selectableItemBackground
和设置背景颜色吗?谢谢!编辑:为了澄清,所讨论的视图不是一个按钮,而是一个
RelativeLayout
。更新:我从未找到一个好的解决办法。最接近的方法是使用
View.setForeground()
将TypedArray
中的Drawable
设置为前景。view.setForeground(typedArray.getDrawable(0));
主要缺点是它只在API 23及以上版本中可用。如果您有更好的解决方案,请让我知道。
Button
。 - weirdo16