编程语言
首页 > 编程语言> > android – 如何以编程方式将selectableItemBackground添加到ImageButton?

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

作者:互联网

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

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

解决方法:

以下是使用答案的示例: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);

标签:attr,r-java-file,android
来源: https://codeday.me/bug/20190926/1821952.html