Programmatically set '?selectableItemBackgroun

2020-02-16 23:49发布

In xml, I often do this to emulate onClick effect:

<android.support.v7.widget.CardView
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:foreground="?selectableItemBackground">

    ...

</android.support.v7.widget.CardView>

Is there any way to access ?selectableItemBackground in java?

5条回答
混吃等死
2楼-- · 2020-02-17 00:15

For those who work with Kotlin, here are some extensions functions to add Ripple on Android View type :

private fun View.addRipple() = with(TypedValue()) {
    context.theme.resolveAttribute(android.R.attr.selectableItemBackground, this, true)
    setBackgroundResource(resourceId)
}

private fun View.addCircleRipple() = with(TypedValue()) {
    context.theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, this, true)
    setBackgroundResource(resourceId)
}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-02-17 00:20

Try below code.

int[] attrs = new int[]{R.attr.selectableItemBackground};
TypedArray typedArray = context.obtainStyledAttributes(attrs);
int backgroundResource = typedArray.getResourceId(0, 0);
cardView.setBackgroundResource(backgroundResource);
cardView.setClickable(true);
typedArray.recycle();
查看更多
The star\"
4楼-- · 2020-02-17 00:25

For appcompat you can use,

TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
cardView.setBackgroundResource(outValue.resourceId);
查看更多
The star\"
5楼-- · 2020-02-17 00:33

I was looking for the same solution. I slightly changed this answer to make it more suitable for the asked question. Call the following code from your constructor.

private void setClickableAnimation(Context context)
{
    TypedValue outValue = new TypedValue();
    context.getTheme().resolveAttribute( 
        android.R.attr.selectableItemBackground, outValue, true);        
    setForeground(getDrawable(context, outValue.resourceId));
}
查看更多
Evening l夕情丶
6楼-- · 2020-02-17 00:36

You should reference it as

android.R.attr.selectableItemBackground

查看更多
登录 后发表回答