如何设置所选项目的颜色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>