我已经发布了相同的问题几次,但还没有解决.我有一个ListFragment,我想突出显示列表中选定的项目.我已经提出使用“选择器”的建议.我不明白如何使用这个选择器.我的ListFragment类是:
// Create an adapter with list of stores and populate the list with // values ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,StoreList); setListAdapter(adapter); mDbHelper.close(); } /* * (non-Javadoc) * * Handles the event when an item is clicked on left pane,performs action * based on the selection in left pane * * @see android.app.ListFragment#onListItemClick(android.widget.ListView,* android.view.View,int,long) */ @Override public void onListItemClick(ListView l,View v,int position,long id) { String selectedStore = (String) getListAdapter().getItem(position); DetailFragment fragment = (DetailFragment) getFragmentManager() .findFragmentById(R.id.detailFragment); if (fragment != null && fragment.isInLayout()) { v.setBackgroundColor(getResources().getColor(R.color.BLUE)); // passes selectedStore to detail fragment fragment.setText(selectedStore); // getItemList(selectedStore); }
使用setBackground永久设置颜色,但是当选择另一个项目时,我希望它消失.
我了解如何在ListView中使用选择器,但在我的情况下,如果我没有为Listview定义任何xml,那么我将如何使用“selector”?我正在使用预定义的android.R.layout.simple_list_item_1.
解决方法
以下为我工作:
RES /颜色/ menu_highlight.xml
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@color/red" /> <item android:state_selected="true" android:drawable="@color/red" /> <item android:drawable="@color/white" /> </selector>
RES /值/ colors.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="white">#FFFFFF</color> <color name="red">#FF0000</color> </resources>
res / layout / menuitem.xml ::(列表中的每个项目的XML)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="fill_parent"> <TextView android:id="@+id/textmenu" android:layout_height="wrap_content" android:text="text" android:textColor="#FFFFFF" android:background="@color/menu_highlight" android:visibility="visible" android:layout_width="fill_parent" /> </LinearLayout>
最后,在ListFragment类中,添加View prevIoUs并将以下代码添加到onlistitemclick函数中(在ListFragment: highlight selected row中提到)
public class MenuListFragment extends ListFragment{ View prevIoUs; @Override public void onListItemClick(ListView l,long id) { super.onListItemClick(l,v,position,id); //Logic to highlight selected item prevIoUs.setSelected(false); v.setSelected(true); prevIoUs=v; } }