更改所选项目的背景色上一个ListView [英] Change background color of selected item on a ListView
问题描述
我想知道我如何能更改选定项的背景颜色在我的ListView。我只是想改变用户点击特定的项目,如果用户点击其他项目将是其突出了一个意思。嗯,因为我希望它保持尽可能简单,使用默认的Android的ListView我用这个code来代替:
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。这是一个绘制的文档作为上述绘制对象用于表示该列表中的当前选择的项目。我也认为,这应该做的伎俩,并是它做的伎俩在我的模拟器却没有关于我的Galaxy Tab。我也尝试过其他方法,但没有什么工作,我希望它是。
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;
}
对于我来说,没有的伎俩。
For me it did the trick.
这篇关于更改所选项目的背景色上一个ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!