如何以程序方式设置android:background ="?android:attr / selectableItemBackground"?

时间:2016-07-22 13:18:18

标签: java android xml

如何以编程方式执行android:background="?android:attr/selectableItemBackground""

我试过了mView.setBackgroundResource(android.R.attr.selectableItemBackground);但它没有用。

1 个答案:

答案 0 :(得分:17)

您需要先解析该属性。

    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);
    }