在循环中突出显示自定义 ListView 项

Highlight Custom ListView Item in Loop

你好,我想更改我的 listView 的背景 item.but 它只突出显示 touch.but 我想更改背景,直到我将焦点更改为其他项目。 我目前所做的如下。

Back.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_enabled="false" android:state_focused="true"
    android:drawable="@android:color/black" />
<item android:state_pressed="true"
    android:drawable="@android:color/holo_red_dark" />
<item android:state_focused="true"
    android:drawable="@android:color/holo_red_dark" />

列表视图

  <ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:fastScrollEnabled="true"
    android:drawSelectorOnTop="true"
    android:clickable="true"
    android:listSelector="@drawable/listviewcolor"
    android:scrollingCache="false">
</ListView>

在 Main 中,我尝试了所有方法,但不起作用,它只能在触摸时突出显示。 但我想在更改之前一直突出显示。

ListView.requestFocus();
        ListView.setActivated(true);
        ListView.setPressed(true);
        ListView.setItemChecked(4, true);
        ListView.requestFocusFromTouch();
        ListView.setSelection(2);

这只能通过以下方式使用 customAdapter 来实现。

最初,当用户触摸布局设计中的其他项目时,Listview 会失去焦点。保持选中状态的一种方法是:

  1. 跟踪从 ListView 中选择的位置。
  2. 使用ListView适配器中的选定位置,并根据选择设置其视图背景颜色。

执行此操作后,您的背景颜色将保持选中状态。

示例: 在您的自定义适配器中

Private  int studentListItemSelected;

public void ItemSelected(int itemPosition)
    {
    //This method will keep track which position of the List is Selected and the background color of it is inside this.
        this.studentListItemSelected=studentListItemSelected;
        notifyDataSetChanged();
    }

 public View getView(int position, View convertView, ViewGroup parent) 
{
 //layout inflation code
  if(this.studentListItemSelected==position)
{
  convertView.setBackgroundColor(Color.Red);
}
else
{
 convertView.setBackgroudnColor(Color.White);
}

  return convertView;
}

在您的布局 Java 文件中:

yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      adapter.ItemSelected(position);

});