开发者

ListFragment Item Selected Background

So I have a ListFragment set up with a few selections that open new Fragments. Part of me is wanting to make each item in the ListFragment (I have around 6) have a different color set for when it is selected and I call my getListView().setItemChecked(index, true); Is it possible to set different backgrounds or do they all have to be the same? 开发者_如何学PythonThanks.


Yes you can have them use a different background. For each of those you will need to build a StateListDrawable that selects the desired background based on the state of the item.

If you look at the Layout fragment demo, the list items use this layout:

setListAdapter(new ArrayAdapter<String>(getActivity(),
        android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));

That layout is:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:gravity="center_vertical"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:minHeight="?android:attr/listPreferredItemHeight"
/>

And the android:background being set here boils down to (for the dark non-holo theme):

<selector xmlns:android="http://schemas.android.com/apk/res/android"
        android:exitFadeDuration="@android:integer/config_mediumAnimTime">
    <item android:state_activated="true"
            android:drawable="@android:drawable/list_selector_background_selected" />
    <item android:drawable="@color/transparent" />
</selector>

So just write your own drawables that use different drawables for their activated state.

(Note I am assuming you are working with Honeycomb where the activated state was introduced. For previous platform versions, this is not as clean but not too hard -- you need to write a layout subclass that implements Checkable and changes its background based on the checked state.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜