如何以编程方式将SelectableItemBackground添加到ImageButton?

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

另外,我将如何去find在文档中的答案? 在这里提到,但是我没有看到如何实际使用的任何解释。 其实,我似乎很少看到文档有用,但我希望这是我的错,而不是文档。

这里是一个使用答案的例子: 如何获取代码中的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 (ie '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); 

如果您使用AppCompat,则可以使用以下代码:

 int[] attrs = new int[]{R.attr.selectableItemBackground}; TypedArray typedArray = context.obtainStyledAttributes(attrs); int backgroundResource = typedArray.getResourceId(0, 0); view.setBackgroundResource(backgroundResource); typedArray.recycle(); 

这适用于我与我的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不是android.R.attr.selectableItemBackground R.attr.selectableItemBackground

我认为typedValue.resourceId保存selectableItemBackground所有drawable,而不是使用TypeArray#getResourceId(index, defValue)TypeArray#getDrawable(index) ,它们只检索给定index处的drawable。

在kotlin中使用这个扩展函数

 fun View.setBackgroundResource() { val outValue = TypedValue() context.theme.resolveAttribute(R.attr.selectableItemBackground,outValue,true) this.backgroundResource = outValue.resourceId }