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

标签 android attr r.java-file

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

关于android - 如何以编程方式将 selectableItemBackground 添​​加到 ImageButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20531516/

相关文章:

jQuery attr() 更改 img src

Android imageView id 不显示

android - 用 MutableLivedata<Cursor> 替换 getLoaderManager().initLoader

java - 帮助进行密码验证

java - 在Android设备上使用Java/Kotlin检测音频文件(amr)中的静音

java - Android 和 Unity3D - Unity 生成的 R.java?

java - ADT 更新后未生成 R.java

android - 单例构造函数使我的应用程序崩溃

jQuery - 如何按属性名称开头选择值

javascript - 为什么 jQuery .prop() 不适用于 'allowfullscreen' ?