Java Android ListView高亮显示所选行

Java Android ListView高亮显示所选行,java,android,xml,listview,Java,Android,Xml,Listview,我试图突出显示listview中选定的项目行。下面是我如何设置listview的: public void buildCatListView(){ //Code to get data from database } // Set the data into listview catlistview.setAdapter(new ListAdapter(this)); catlistview.setOnItemClickListener(new Ad

我试图突出显示listview中选定的项目行。下面是我如何设置listview的:

 public void buildCatListView(){
    //Code to get data from database

    }
    // Set the data into listview
    catlistview.setAdapter(new ListAdapter(this));

    catlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View item,
                int position, long id) {

            // Get the transaction record ID
            categoryID = _catlist.get(position)
                    .getCategoryID();

            for (int j = 0; j < parent.getChildCount(); j++)
                parent.getChildAt(j).setBackgroundColor(Color.WHITE);
            // Change the background color of the selected element
            item.setBackgroundColor(Color.rgb(246, 206, 206));
        }
    });
    mDbHelper.close();
}
public void buildCatListView(){
//从数据库获取数据的代码
}
//将数据设置为listview
setAdapter(新的ListAdapter(this));
catlistview.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父项、视图项、,
内部位置,长id){
//获取事务记录ID
categoryID=\u catlist.get(位置)
.getCategoryID();
对于(int j=0;j
以及我的列表视图的XML文件:

<ListView
    android:id="@+id/listview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
</ListView>

以及“我的列表视图”行的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" 
android:padding="5dp">

<TextView
    android:id="@+id/txtDisplayCat"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="15dp" />

<TextView
    android:id="@+id/txtDisplayCatDesc"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="10dp" />

</LinearLayout>

单击时,它确实高亮显示了所选行。但它的表现非常怪异。假设我选择了第一项,它不仅突出显示了第一项,还突出显示了最后一项。然后向下滚动时,高亮显示的行有时会移到第二行或第三行。我不知道为什么会这样

只是想知道有没有其他方法可以做到这一点


提前感谢。

尝试使用
列表视图的此属性

android:listSelector="#99000000" 

您也可以创建自己的选择器,并将其设置为背景可绘制

非常感谢!它起作用了!但是为什么当我在列表视图中滚动时,高亮度的颜色会保留在列表视图的顶部或底部?