取消选择 ListView 中的项目

Deselect item in ListView

场景是这样的: 在 ListView 中,我希望所选项目保持选中状态,直到用户单击 DialogFragment 按钮。问题是,如果用户单击后退按钮,但没有在 DialogView 中进行任何单击,ListView 中的项目仍然处于选中状态。

我读过 this post ,解决方案效果很好:我点击一个项目,出现对话框,我点击后退按钮,选择器消失了。

但是如果我滚动列表,选择器就会回来!我哪里错了?

这里是代码:

<ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/listView"
        android:layout_gravity="center"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="15dp"
        android:divider="@android:color/transparent"
        android:visibility="visible"
        android:dividerHeight="5dp"
        android:choiceMode="singleChoice"
        android:drawSelectorOnTop="true"
        android:listSelector="@color/primario_1_alfa"/>

以及我尝试取消选择列表视图元素的 DialogFragment

public class MyDialog extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("Test dialog view")
                .setPositiveButton("action 1", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                })
                .setNegativeButton("action 2", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
        return builder.create();
    }
    @Override
    public void onDestroy(){
        super.onDestroy();
        ListView listView = (ListView) getActivity().findViewById(R.id.listView);
        listView.clearChoices();
        listView.requestLayout();
    }
}

这是由于使用 ViewHolder 模式回收了视图。

由于您在任何时候都只需要一个 select 项,因此您可以跟踪 select 在适配器中编辑的项的位置,然后根据当前位置检查该位置要用 ViewHolder 数据填充的视图的位置。

int selectedPosition;
...
onItemClickListener(int position, ...) {
   selectedPosition = position;
}
...
getView(int position, ...) {

   if (selectedPosition == position) {
      view.setSelected(true);
   } else {
      view.setSelected(false);
   }
}

类似的东西。