Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmitically set android:background="?android:attr/selectableItemBackground"?

Tags:

java

android

xml

How can I do android:background="?android:attr/selectableItemBackground"" programmatically?

I tried mView.setBackgroundResource(android.R.attr.selectableItemBackground); and it didn't work.

like image 889
John Sardinha Avatar asked Jul 22 '16 13:07

John Sardinha


1 Answers

You need to resolve the attribute first.

    TypedValue typedValue = new TypedValue();

    // I used getActivity() as if you were calling from a fragment.
    // You just want to call getTheme() on the current activity, however you can get it
    getActivity().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, typedValue, true);

    // it's probably a good idea to check if the color wasn't specified as a resource
    if (typedValue.resourceId != 0) {
        mView.setBackgroundResource(typedValue.resourceId);
    } else {
        // this should work whether there was a resource id or not
        mView.setBackgroundColor(typedValue.data);
    }
like image 69
kris larson Avatar answered Sep 28 '22 02:09

kris larson