如何设置所选项目的颜色ListFragment在android系统? [英] How to set color of selected item in ListFragment in android?

查看:128
本文介绍了如何设置所选项目的颜色ListFragment在android系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个<击>列表视图 ListFragment 它会从一个适配器填充,我想强调在列表中点击(或选择)项以及做基于一些行动上的选择。我能处理该事件,但我如何设置所选项目从列表中选择颜色。

I have a listview ListFragment which gets populated from an adapter, I want to highlight the clicked (or selected) item in the list as well as do some action based on the selection. I am able to handle the event but How do I set the color of selected item from the list.

推荐答案

如果您使用的是ListFragment,那么你可能无法在指定XML一个ListView这意味着你需要设置$ C $的listSelector C。要小心,不要将其设置在活动周期为时尚早,虽然你会用一个IllegalStateException结束。

If you're using a ListFragment then you might not be specifying a ListView in XML which means you'll need to set the 'listSelector' in code. Be careful not to set it too early in the activity lifecycle though as you'll end up with an IllegalStateException.

level_list_selector.xml

level_list_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/level_gradient_bg" />

    <item android:state_pressed="true android:drawable="@drawable/level_gradient_bg_hover" />

    <item android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/level_gradient_bg_hover" />
</selector>

片段:

public class LevelFragment extends ListFragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       //Create view 
       ...
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        getListView().setSelector(R.drawable.level_list_selector);
    }
}

请注意:如果你使用自定义布局单元格的行,你需要在该设置列表中选择太

Note: if you're using a custom layout for the cell rows, you'll need to set the list selector on that too.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@drawable/level_list_selector"
    android:padding="5dip" >
...
</RelativeLayout>

这篇关于如何设置所选项目的颜色ListFragment在android系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆