How do I add selectableItemBackground to an ImageButton programmatically?

abc32112 picture abc32112 · Dec 11, 2013 · Viewed 32.6k times · Source

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

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.

Answer

Timuçin picture Timuçin · Dec 12, 2013

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