如何通过编程方式设置android:background="?android:attr/selectableItemBackground"?

11
我该如何在程序中实现 android:background="?android:attr/selectableItemBackground"?我尝试使用 mView.setBackgroundResource(android.R.attr.selectableItemBackground);,但没有起作用。
1个回答

27

您需要先解决属性问题。

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

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