How do I add selectableItemBackground to an ImageButton programmatically?
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);
If you are using AppCompat you could use following code:
int[] attrs = new int[]{R.attr.selectableItemBackground};TypedArray typedArray = context.obtainStyledAttributes(attrs);int backgroundResource = typedArray.getResourceId(0, 0);view.setBackgroundResource(backgroundResource);typedArray.recycle();
This works for me with my TextView
:
// Get selectable backgroundTypedValue typedValue = new TypedValue();getTheme().resolveAttribute(R.attr.selectableItemBackground, typedValue, true);clickableTextView.setClickable(true);clickableTextView.setBackgroundResource(typedValue.resourceId);
Because I use AppCompat library, I use R.attr.selectableItemBackground
not android.R.attr.selectableItemBackground
.
I think typedValue.resourceId
holds all drawables from selectableItemBackground
than using TypeArray#getResourceId(index, defValue)
or TypeArray#getDrawable(index)
which are retrieve only a drawable at the given index
.