【问题标题】:ListFragment Item Selected BackgroundListFragment 项目选定背景
【发布时间】:2011-03-16 20:51:26
【问题描述】:

所以我设置了一个 ListFragment,其中包含一些打开新片段的选项。我的一部分是想让 ListFragment 中的每个项目(我大约有 6 个)在被选中时设置不同的颜色,我打电话给我的 getListView().setItemChecked(index, true); 是否可以设置不同的背景或者它们都必须相同?谢谢。

【问题讨论】:

    标签: android listview


    【解决方案1】:

    是的,您可以让它们使用不同的背景。对于其中的每一个,您都需要构建一个 StateListDrawable,它根据项目的状态选择所需的背景。

    如果您查看 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:background 归结为(对于黑暗的非全息主题):

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

    因此,只需编写您自己的可绘制对象,将不同的可绘制对象用于激活状态。

    (注意,我假设您正在使用 Honeycomb,其中引入了激活状态。对于以前的平台版本,这不是很干净但也不太难——您需要编写一个实现 Checkable 并更改其背景的布局子类基于选中状态。)

    【讨论】:

    • 文字颜色呢?我可以使用相同的技术吗?
    • 是的,虽然它需要是一个可以改变的颜色资源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 2020-12-27
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多