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

wei*_*o16 6 android android-view android-drawable android-attributes

我有一个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);
}
Run Code Online (Sandbox Code Playgroud)

任何人都知道我如何使用两者?attr/selectableItemBackground并设置背景颜色?谢谢!

编辑: 澄清一下,有问题的视图不是按钮,而是RelativeLayout.

更新: 我从来没有真正找到一个好的解决方案。我得到的最接近的是使用View.setForeground()到 a Drawablefrom the TypedArray,即

view.setForeground(typedArray.getDrawable(0));
Run Code Online (Sandbox Code Playgroud)

这样做的主要缺点是它仅适用于 API 23+。如果您想出更好的解决方案,请告诉我。

Ogn*_*kov 1

我建议创建一个自定义,您可以在其中从 xmlView获取pressedColor,defaultColor和。disabledColor

以下代码适用于 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);
}
Run Code Online (Sandbox Code Playgroud)