Android ListView突出显示所选行

时间:2014-08-30 07:07:57

标签: java android xml 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();
}

我的列表视图的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>

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

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

提前致谢。

1 个答案:

答案 0 :(得分:0)

尝试使用ListView

的此属性
android:listSelector="#99000000" 

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

相关问题