将?attr/selectableItemBackground添加到View并设置背景颜色

6

我创建了一个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及以上版本中可用。如果您有更好的解决方案,请让我知道。


请参见以下链接:https://dev59.com/Bl8d5IYBdhLWcg3wkS0V - Chantell Osejo
谢谢@ChantellOsejo,但是我尝试了那个答案并没有成功,而且我也没有使用Button - weirdo16
1个回答

1
我建议创建一个自定义的 View,您可以从xml中获取pressedColordefaultColordisabledColor
以下代码适用于Material样式的按钮:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
    ColorStateList colorStates = new ColorStateList(
            new int[][]{
                    new int[]{android.R.attr.state_pressed},
                    new int[]{}
            },
            new int[]{
                    pressedColor,
                    defaultColor});

    view.setBackgroundDrawable(isEnabled ? new RippleDrawable(colorStates, getBackground(), getBackground())
            : new ColorDrawable(disabledColor);
}
else
{
    StateListDrawable backgroundDrawable = new StateListDrawable();
    backgroundDrawable.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(isEnabled ?
            pressedColor : disbledColor));
    backgroundDrawable.addState(StateSet.WILD_CARD, new ColorDrawable(isEnabled ? defaultColor :
            disabledColor));
    view.setBackgroundDrawable(backgroundDrawable);
}

谢谢Ognian,RippleDrawableStateListDrawable都显示了涟漪效果,但背景色没有改变。 - weirdo16

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