如何以编程方式将selectableItemBackground添加到ImageButton?

时间:2013-12-11 22:45:59

标签: android attr r.java-file

android.R.attr.selectableItemBackground存在,但是如何以编程方式将其添加到ImageButton?

另外,我如何在文档中找到答案?它被提到here,但我没有看到它是如何实际使用的任何解释。实际上,我似乎很少发现文档有用,但我希望这是我的错,而不是文档的错误。

4 个答案:

答案 0 :(得分:53)

以下是使用答案的示例:How to get the attr reference in code?

    // Create an array of the attributes we want to resolve
    // using values from a theme
    // android.R.attr.selectableItemBackground requires API LEVEL 11
    int[] attrs = new int[] { android.R.attr.selectableItemBackground /* index 0 */};

    // Obtain the styled attributes. 'themedContext' is a context with a
    // theme, typically the current Activity (i.e. 'this')
    TypedArray ta = obtainStyledAttributes(attrs);

    // Now get the value of the 'listItemBackground' attribute that was
    // set in the theme used in 'themedContext'. The parameter is the index
    // of the attribute in the 'attrs' array. The returned Drawable
    // is what you are after
    Drawable drawableFromTheme = ta.getDrawable(0 /* index */);

    // Finally free resources used by TypedArray
    ta.recycle();

    // setBackground(Drawable) requires API LEVEL 16, 
    // otherwise you have to use deprecated setBackgroundDrawable(Drawable) method. 
    imageButton.setBackground(drawableFromTheme);
    // imageButton.setBackgroundDrawable(drawableFromTheme);

答案 1 :(得分:50)

如果您使用的是AppCompat,则可以使用以下代码:

int[] attrs = new int[]{R.attr.selectableItemBackground};
TypedArray typedArray = context.obtainStyledAttributes(attrs);
int backgroundResource = typedArray.getResourceId(0, 0);
view.setBackgroundResource(backgroundResource);
typedArray.recycle();

答案 2 :(得分:8)

这适用于我的TextView

// Get selectable background
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.selectableItemBackground, typedValue, true);

clickableTextView.setClickable(true);
clickableTextView.setBackgroundResource(typedValue.resourceId);

因为我使用AppCompat库,所以我使用R.attr.selectableItemBackground而不是android.R.attr.selectableItemBackground

我认为typedValue.resourceId包含来自selectableItemBackground的所有drawable,而不是TypeArray#getResourceId(index, defValue)TypeArray#getDrawable(index),它们只能检索给定index的drawable。

答案 3 :(得分:3)

试试这个方法:

public Drawable getDrawableFromAttrRes(int attrRes, Context context) {
    TypedArray a = context.obtainStyledAttributes(new int[] {attrRes});
    try {
        return a.getDrawable(0);
    } finally {
        a.recycle();
    }
}

//然后就这样打电话:

getDrawableFromAttrRes(R.attr.selectableItemBackground, context)

// Example
ViewCompat.setBackground(view,getDrawableFromAttrRes(R.attr.selectableItemBackground, context))