我想知道如何更改listView上所选项目的背景颜色.我只想更改用户点击的特定项目,这意味着如果用户点击另一个项目,它将是突出显示的项目.好吧,因为我希望它尽可能保持简单并使用默认的android listview我使用此代码:
record_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
try{
for (int ctr=0;ctr<=record_items.length;ctr++){
if(i==ctr){
record_list.getChildAt(ctr).setBackgroundColor(Color.CYAN);
}else{
record_list.getChildAt(ctr).setBackgroundColor(Color.WHITE);
}
}
}
catch (Exception e){
e.printStackTrace();
}
Log.v("Selected item",record_list.getItemAtPosition(i));
}
});
Run Code Online (Sandbox Code Playgroud)
好的,这个工作正常,但问题是它很慢.现在我想知道是否有任何其他方法可以做到,它将提供与我相同的输出.
我尝试使用record_list.getSelectedView().setBackgroundColor(Color.CYAN);但它给了我一个空指针异常.
我也尝试了selector.xml,但它也没有做到这一点.此外,ListView上有一个名为listSelector的属性.如文档"Drawable用于指示列表中当前选定的项目"所述,它是可绘制的.我也相信这应该可以做到这一点,是的,它可以在我的模拟器上完成,但不是在我的Galaxy选项卡上.我也尝试了其他方法,但没有任何方法可行,因为我想要它.
我正在尝试将选择器应用于ListView,以便那些没有触摸屏的人可以轻松浏览我的应用程序.问题是,通过将选择器应用于ListView,它似乎只将背景颜色应用于整个列表,而不是其中的项目.
有任何想法吗?这是一些代码:
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:listSelector="@drawable/listselector"
/>
<TextView android:id="@android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="There are no Clients yet."
/>
Run Code Online (Sandbox Code Playgroud)
drawable文件夹中的listselector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector
android:id="@+id/myselector"
xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Non focused states -->
<item
android:state_focused="false"
android:state_selected="false"
android:state_pressed="false"
android:drawable="@color/darkblue" />
<item
android:state_focused="false"
android:state_selected="true"
android:state_pressed="false"
android:drawable="@color/green" />
<!-- Focused states -->
<item
android:state_focused="true"
android:state_selected="false"
android:state_pressed="false"
android:drawable="@color/green" />
<item
android:state_focused="true"
android:state_selected="true"
android:state_pressed="false"
android:drawable="@color/green" />
<!-- Pressed -->
<item
android:state_pressed="true"
android:drawable="@color/green" />
</selector>
Run Code Online (Sandbox Code Playgroud) 我有一个Android列表视图.我想在单击一个listview项目时更改listview项目背景.
然后,之前选择的项目必须返回默认背景.这意味着只需要选择一个项目.
我已经搜索了很长时间了.我可以使用onItemClick()更改所选项目的背景
但我不能改变以前选择的项目.例如,如果我选择第二个项目,它就会被更改.然后我选择第三项.哦,我的上帝!它也改变了!我能为此做些什么 我怎么能得到以前的位置?
这是我的android代码.
private class ListViewItemClickListener implements
AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView title = (TextView) view.findViewById(R.id.title);
title.setBackgroundResource(R.drawable.list_shape);
}
}
Run Code Online (Sandbox Code Playgroud)