8

我有一个 9patch 设置为我的布局的背景。但是我仍然想通过使用selectableItemBackgroundattr 来提供触摸反馈。

我已经尝试将 a<layer-list>与 9patch 和selectableItemBackground作为android:drawablesecond一起使用<item>,但这不起作用。

我也可以尝试制作一个选择器并selectableItemBackground用. 但是在 4.4 KitKat 中,JellyBeans 中选择的背景颜色实际上是灰色而不是蓝色,所以我不能真正对其进行硬编码:(list_selector_background_pressed.xml<layer-list>

必须有一个更简单的方法,对吧?丁:

4

1 回答 1

16

我尝试使用 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"
于 2013-12-02T22:17:07.007 回答