ListFragment项目选择的背景背景、项目、ListFragment

2023-09-04 03:07:42 作者:微不足道的关心收下吧。

所以我有一个ListFragment设置了几个选择打开新的片段。 。我的一部分是想使每个项目在ListFragment(我有大约6)有不同的颜色设置为被选中时,我打电话给我的 getListView()setItemChecked(指数,真正的); 是否可以设置不同的背景,还是他们都必须是一样的吗?谢谢。

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? Thanks.

推荐答案

是的,你可以让他们使用不同的背景。对于每个那些你需要建立一个StateListDrawable,基于项目的状态,选择所需的背景。

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));

这布局是:

<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"
/>

和android:背景在这里被设置归结为(为暗无全息主题):

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.

(注意:我假设你正在使用蜂窝引入激活状态为previous平台的版本,这是不是干净的,但不能太硬 - 你需要编写实现辨认和布局子变化的基础上的选中状态的背景。)

(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.)