我尝试使用 9patch 和 selectableItemBackground 作为第二个的 android:drawable ,但是没有用。
是的,图层列表(或状态列表)中的可绘制属性不接受attr
值。你会看到一个Resource.NotFoundException
. 查看 LayerDrawable(或 StateListDrawable)的源代码可以解释原因:您提供的值被假定为可绘制对象的 id。
但是,您可以在代码中为属性检索主题和特定于平台的可绘制对象:
// Attribute array
int[] attrs = new int[] { android.R.attr.selectableItemBackground };
TypedArray a = getTheme().obtainStyledAttributes(attrs);
// Drawable held by attribute 'selectableItemBackground' is at index '0'
Drawable d = a.getDrawable(0);
a.recycle();
现在,您可以创建一个LayerDrawable
:
LayerDrawable ld = new LayerDrawable(new Drawable[] {
// Nine Path Drawable
getResources().getDrawable(R.drawable.Your_Nine_Path),
// Drawable from attribute
d });
// Set the background to 'ld'
yourLayoutContainer.setBackground(ld);
您还需要设置yourLayoutContainer's clickable
属性:
android:clickable="true"