问题
I have a list where I have defined my own list view items with a custom layout. This layout has a background with a custom drawable.
My custom layout for the ListView item:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/item"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true" >
...
</RelativeLayout>
My custom drawable item.xml
:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- background: shadow -->
<item>
<shape
android:dither="true"
android:shape="rectangle" >
<corners android:radius="2dp" />
<solid android:color="@color/itemShadowColor" />
</shape>
</item>
<!-- foreground: surface -->
<item android:bottom="2dp">
<shape
android:dither="true"
android:shape="rectangle" >
<corners android:radius="2dp" />
<solid android:color="@color/itemBackgroundColor" />
</shape>
</item>
</layer-list>
Now this item is not clickable anymore.
Can you explain me why, and what I have to do to have the same behavior (selector with the blue background) like a button click?
回答1:
Define a selector
with its pressed
and default
states in res/drawable
folder(one of the state will be your @drawable/item
). Set it as the bg of your list row layout.
See similar question and answer :Selector on background color of TextView
Edit:
Best way to understand and apply something like google did is, to look into SDK and do similar things to that. For instance look at the btn_default_holo_dark
drawable. It is a selector with states and yes it is a xml.
This is a selector taken from sdk (sdk\platforms\android-18\data\res\drawable\btn_default_holo_dark.xml
)
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false" android:state_enabled="true"
android:drawable="@drawable/btn_default_normal_holo_dark" />
<item android:state_window_focused="false" android:state_enabled="false"
android:drawable="@drawable/btn_default_disabled_holo_dark" />
<item android:state_pressed="true"
android:drawable="@drawable/btn_default_pressed_holo_dark" />
<item android:state_focused="true" android:state_enabled="true"
android:drawable="@drawable/btn_default_focused_holo_dark" />
<item android:state_enabled="true"
android:drawable="@drawable/btn_default_normal_holo_dark" />
<item android:state_focused="true"
android:drawable="@drawable/btn_default_disabled_focused_holo_dark" />
<item
android:drawable="@drawable/btn_default_disabled_holo_dark" />
</selector>
These are the images taken from sdk (sdk\platforms\android-18\data\res\drawable-xhdpi
):
When you apply this drawable/selector (@drawable/btn_default_holo_dark
) to any view, you are going to have its states. I hope this sample makes my answer more clear.
来源:https://stackoverflow.com/questions/19845139/android-make-list-item-with-background-clickable