更改 ListView 上所选项目的背景颜色 [英] Change background color of selected item on a ListView
问题描述
我想知道如何更改 listView 上所选项目的背景颜色.我只想更改用户单击的特定项目,这意味着如果用户单击另一个项目,它将是突出显示的项目.好吧,因为我希望它尽可能保持简单并使用默认的 android 列表视图,所以我改用了以下代码:
I want to know on how I can change the background color of the selected item on my listView. I only want to change the specific item clicked by the user, meaning if the user clicks another item it will be the one which is highlighted. Well since I want it to keep simple as possible and use the default android listview I used this code instead:
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));
}
});
好的,这个工作正常,但问题是它很慢.现在我想知道是否还有其他方法可以提供与我所做的相同的输出.
Ok this one is working but the problem is that it's slow. Now I want to know if there's any other way around that I can do which will give the same output as I made.
我尝试使用 record_list.getSelectedView().setBackgroundColor(Color.CYAN);
但它给了我一个空指针异常.
I tried using record_list.getSelectedView().setBackgroundColor(Color.CYAN);
but it gives me a null pointer exception.
我也尝试过 selector.xml 但它也没有成功.此外,ListView 上有一个属性,称为 listSelector.正如文档Drawable 用于指示列表中当前选定的项目"所述,它是一个可绘制对象.我也相信这应该可以解决问题,是的,它可以在我的模拟器上完成,但不能在我的 Galaxy 选项卡上完成.我也尝试了其他方法,但没有任何效果如我所愿.
I also tried the selector.xml but it also didn't do the trick. Furthermore, there is one properties here on ListView which is called listSelector. It's a drawable as said by the documentation "Drawable used to indicate the currently selected item in the list." I also believe that this should do the trick and yes it do the trick on my emulator but not on my galaxy tab. I also tried the other methods but nothing works as I wanted it to be.
推荐答案
可以跟踪当前选中元素的位置:
You can keep track the position of the current selected element:
OnItemClickListener listViewOnItemClick = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View arg1, int position, long id) {
mSelectedItem = position;
mAdapter.notifyDataSetChanged();
}
};
并覆盖适配器的 getView 方法:
And override the getView method of your adapter:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final View view = View.inflate(context, R.layout.item_list, null);
if (position == mSelectedItem) {
// set your color
}
return view;
}
对我来说它成功了.
这篇关于更改 ListView 上所选项目的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!