android.R.attr.selectableItemBackground存在,但我该如何在ImageButton中以编程方式添加它?
另外,我该如何在文档中找到答案? 它在这里提到过,但我没有看到任何有关实际使用的说明。 实际上,我很少发现文档有用,但我希望这不是文档的问题,而是我的问题。
android.R.attr.selectableItemBackground存在,但我该如何在ImageButton中以编程方式添加它?
另外,我该如何在文档中找到答案? 它在这里提到过,但我没有看到任何有关实际使用的说明。 实际上,我很少发现文档有用,但我希望这不是文档的问题,而是我的问题。
这里是一个使用answer here的例子:如何在代码中获取属性引用?
// 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);
View.setForeground(Drawable)
而不是setBackground()
。 - Richard Le Mesurier如果您正在使用AppCompat,您可以使用以下代码:
int[] attrs = new int[]{R.attr.selectableItemBackground};
TypedArray typedArray = context.obtainStyledAttributes(attrs);
int backgroundResource = typedArray.getResourceId(0, 0);
view.setBackgroundResource(backgroundResource);
typedArray.recycle();
setClickable(true)
和 setFocusable(true)
。 - M. Reza Nasirloo这适用于我使用的TextView
:
// Get selectable background
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.selectableItemBackground, typedValue, true);
clickableTextView.setClickable(true);
clickableTextView.setBackgroundResource(typedValue.resourceId);
R.attr.selectableItemBackground
而不是android.R.attr.selectableItemBackground
。typedValue.resourceId
包含了所有来自selectableItemBackground
的可绘制物,而不是仅使用TypeArray#getResourceId(index, defValue)
或TypeArray#getDrawable(index)
只能检索给定index
处的一个可绘制物。请尝试以下方法:
public Drawable getDrawableFromAttrRes(int attrRes, Context context) {
TypedArray a = context.obtainStyledAttributes(new int[] {attrRes});
try {
return a.getDrawable(0);
} finally {
a.recycle();
}
}
// 然后只需要像这样调用它:
getDrawableFromAttrRes(R.attr.selectableItemBackground, context)
// Example
ViewCompat.setBackground(view,getDrawableFromAttrRes(R.attr.selectableItemBackground, context))
R.attr.selectableItemBackground
,所以用android.R.attr.selectableItemBackground
替换可能更安全。 - Mr-IDE