如何以编程方式将selectableItemBackground添加到ImageButton? [英] How do I add selectableItemBackground to an ImageButton programmatically?

查看:156
本文介绍了如何以编程方式将selectableItemBackground添加到ImageButton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

android.R.attr.selectableItemBackground exists, but how do I add it programatically to an ImageButton?

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

Also, how would I go about finding the answer in the documentation? It's mentioned here, but I don't see any explanation of how it's actually used. Actually, I rarely seem to find the documentation useful, but I'm hoping that's my fault and not that of the documentation.

推荐答案

这里是一个使用答案的示例:如何获取attr参考代码?

Here is an example using answer 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);

这篇关于如何以编程方式将selectableItemBackground添加到ImageButton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆