我有一个 ListView 和 listselector.xml。最初我使用 setSeletion(position) 设置该项目。但使用此代码该项目不会突出显示。仅当我单击某个项目时它才会突出显示。
ArrayAdapter<String> ad = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
timeListView = (ListView) findViewById(R.id.listList);
timeListView.setAdapter(ad);
timeListView.setOnItemClickListener(this);
timeListView.setSelector(R.drawable.listselector);
timeListView.setSelection(toSelectPos);
=============================
XML
<ListView android:id="@+id/listList" android:layout_width="match_parent" android:layout_height="wrap_content" android:dividerHeight="1dp" >
listselector.xml代码
<?xml version="1.0" encoding="UTF-8"?>
<!-- listselector.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Selected -->
<item android:state_focused="true" android:state_selected="false"
android:drawable="@drawable/focused"/>
<!-- Pressed -->
<item android:state_selected="true" android:state_focused="false"
android:drawable="@drawable/selected" />
</selector>
上面的代码突出显示完整的列表视图,我只想突出显示(更改背景颜色)该项目。为此,我相信我必须为该项目创建另一个 xml,并为该项目设置选择器属性,而不是像上面那样列出。如果错了请纠正我。
关键是,无论如何,只有单击和 setSelection 上的选定项目才应该更改。使用上面的代码,它不会改变 setSelection,如何实现这一点。
我查看了其他问题,但找不到我要找的点,所以请不要将其标记为其他问题的重复项。
Thanks
我不确定这是否正确,但我从 support-v4 示例的片段演示中找到了以下解决方案。
制作可检查的自定义布局并将此布局用于列表行
public class CheckableLayout extends LinearLayout implements Checkable {
private boolean mChecked;
public CheckableLayout (Context context) {
super(context);
}
public CheckableLayout (Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setChecked(boolean checked) {
mChecked = checked;
// set the custom background image/color
setBackgroundResource(checked ? R.drawable.category_item_row_selected
: R.drawable.custom_category_item_row);
}
public boolean isChecked() {
return mChecked;
}
public void toggle() {
setChecked(!mChecked);
}
}
将列表视图定义为单选模式,例如YOUR_LISTVIEW.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
单击行(inside OnItemClickListener
)你必须将该行设置为选中状态,例如YOUR_LISTVIEW.setItemChecked(index, true);
Thats it
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)