Как я могу добавить selectableItemBackground в ImageButton программно?
android.R.attr.selectableItemBackground существует, но как добавить его программно в ImageButton?
Кроме того, как я могу найти ответ в документации? Он упомянул здесь, но я не вижу никакого объяснения того, как он на самом деле используется. На самом деле, я редко вижу, что документация полезна, но я надеюсь, что моя вина, а не документация.
Ответы
Ответ 1
Вот пример использования ответа здесь: Как получить ссылку attr в коде?
// 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);
Ответ 2
Если вы используете AppCompat, вы можете использовать следующий код:
int[] attrs = new int[]{R.attr.selectableItemBackground};
TypedArray typedArray = context.obtainStyledAttributes(attrs);
int backgroundResource = typedArray.getResourceId(0, 0);
view.setBackgroundResource(backgroundResource);
typedArray.recycle();
Ответ 3
Это работает для меня с моим TextView
:
// Get selectable background
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.selectableItemBackground, typedValue, true);
clickableTextView.setClickable(true);
clickableTextView.setBackgroundResource(typedValue.resourceId);
Поскольку я использую библиотеку AppCompat, я использую R.attr.selectableItemBackground
not android.R.attr.selectableItemBackground
.
Я думаю, что typedValue.resourceId
содержит все чертежи от selectableItemBackground
, чем использование TypeArray#getResourceId(index, defValue)
или TypeArray#getDrawable(index)
, которые извлекают только вытачиваемый при заданном index
.