现在我用的:
android:listSelector="@drawable/bg_list_item"
android:drawSelectorOnTop="true"
在这里bg_list_item.xml:
where bg_list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<item android:state_selected="true">
<shape android:shape="rectangle">
<gradient android:startColor="#0000ff"/>
</shape>
</item>
<item android:state_focused="false"
android:state_pressed="false"
android:state_selected="false">
<shape android:shape="rectangle">
<gradient android:startColor="#ff0000"/>
</shape>
</item>
但第一项不工作,选择的项目是不是有时滚动高亮(当我接近我的列表视图顶部/底部),从来没有在listView.setSelection(指数)。
BUT first item is not working and selected item is not highlighting sometimes on scroll (when I am near top/bottom of my listview) and never on listView.setSelection(index).
难道我一定要强调当前项目programmaticaly?
Does I must to highlight current item programmaticaly?
定义一个定制适配器,并在其getView()方法:
define a custom adapter and in its getView() method:
private int selectedItem;
// is used outside the adapter for example OnItemClickListener
public void setSelectedItem(int position) {
selectedItem = position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//...
// set selected item
LinearLayout activeItem = (LinearLayout) rowView;
if (position == selectedItem)
{
activeItem.setBackgroundResource(R.drawable.background_dark_blue);
}
else
{
activeItem.setBackgroundResource(R.drawable.border02);
}
//...
}
background_dark_blue.xml
background_dark_blue.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="@color/lightBlue6" />
<!-- border width and color -->
<stroke
android:width="2dp"
android:color="#FF0404B4" />
<padding
android:bottom="2dp"
android:left="2dp"
android:right="2dp"
android:top="2dp" />
</shape></item>
</layer-list>
border02.xml
border02.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle" android:layout_width="wrap_content">
<stroke android:width="0.5dp" android:color="#FF000000" />
<solid android:color="#FFFFFFFF" />
<padding android:left="0dp" android:top="0dp" android:right="0dp"
android:bottom="0dp" />
<corners android:radius="0dp" />
</shape>
</item>
</layer-list>