在陈词滥调时更改listview项目背景

我有一个listview,我想当我点击一行时,它的背景变为蓝色。 我用这个代码:

listView1.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View view, int position, long id) { // TODO Auto-generated method stub parent.getChildAt(position).setBackgroundColor(Color.BLUE); } }); 

这有点错误。 当我点击第一个项目时,它变为蓝色,但项目#3和#5也变为蓝色! 我不明白为什么!! 我只想要只选择项目变成蓝色!!!

如何使用选择器? 它们正常工作并提供清洁的解决方案

listselector.xml

       

normal.xml

     

hover.xml

     

用法

  

关键属性是为ListView设置android:listSelector="@drawable/listselector"

注意:

您可以在形状中使用渐变属性而不是纯色。 有关更多详细信息,您还可以查看教程Android Custom ListView 。

如果您有自定义列表视图,请使用以下代码。

  public View getView(final int arg0, View arg1, ViewGroup arg2) { final ViewHolder vh; vh= new ViewHolder(); if(arg1==null ) { arg1=mInflater.inflate(R.layout.lyourcustomlayouttobe inflated, arg2,false);//custom layout inflated arg1.setTag(vh); } return arg1; 

}

您的自定义布局

    //other items to be inlfated.  

在资源下创建一个可绘制文件夹。 将下面的xml发布为listviewbkg

       

在drawable下使用名称normal.xml时的正常形状

    //change color //border color     

在drawable文件夹中名为pressed.xml的情况下按下时的形状

     //change color //border color    

使用listselectors来实现这个目标:

Hree就是一个例子: http : //www.michenux.net/android-listview-highlight-selected-item-387.html

如果你想让你的listview项颜色永久化,那么,你需要创建一个选定位置的array ,在你的cutom适配器的getview()方法中,你需要检查该位置是否存在于数组中,如果是,然后手动更改视图的背景颜色