每当用户按下列表视图时,它会将其背景颜色更改为红色。但是,当我按下另一个项目时,旧项目仍然保留红色的背景颜色。如何编辑它,使得只有被点击的项目的背景颜色发生了变化。
lvContact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
view.setSelected(true);
view.setBackgroundColor(Color.RED);
nameSelected = contactHolderArrayList.get(position).name;
phoneSelected = contactHolderArrayList.get(position).phone;
//Anything
}
});
答案 0 :(得分:0)
我刚刚实施了一个简单的计数器来跟踪上一个和当前位置,它的确有效!如果有任何问题请评论。我在oncreate中将计数器初始化为0,并在每次按下列表项时递增,然后包含在onitemclicklistener中的代码下面
lvContact.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
//view.setSelected(true);
if(counter==0) {
prevPosition = position;
}
else if (counter ==1) {
currentPosition = position;
}
else {
prevPosition = currentPosition;
currentPosition = position;
}
lvContact.getChildAt(prevPosition).setBackgroundColor(Color.TRANSPARENT);
view.setBackgroundColor(Color.RED);
counter++;
答案 1 :(得分:-1)
你需要在ListView适配器的视图上应用onTouchListener,然后需要在Down动作上设置新的Color,在Up动作上设置Old color
public View getView(int position, View convertView, ViewGroup parent)
{
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
// apply new color
}
if(event.getAction() == MotionEvent.ACTION_UP){
// apply old color
}
return false;
}
});
return view;
}