Android - 切换按钮在滚动 ListView 后失去其状态

Android - ToggleButton losses it's state after scrolling ListView

我这两天一直在尝试解决这个问题。我已经看到很多与此问题相关的问题。但它们对我不起作用。
我有一个习惯 ListView。它的每一行包括一个ImageView、两个TextView和一个ToggleButton。这些都很好。当我将 ToggleButton 的状态更改为 true 时,当我向下滚动并再次向上滚动时,ToggleButton 失去了它的状态。这又是 false

这是我的 ArrayAdapter

private class MyAdapter extends ArrayAdapter<String> {

    public MyAdapter(Context context, int resource, int textViewResourceId,
            String[] strings) {
        super(context, resource, textViewResourceId, strings);
        // TODO Auto-generated constructor stub
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        LayoutInflater inflater  = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.friends_list_item_layout, parent, false);

        RoundedImageView friendThumb = (RoundedImageView) row.findViewById(R.id.friendDp);
        TextView friendName = (TextView) row.findViewById(R.id.friendName);
        TextView friendNumber = (TextView) row.findViewById(R.id.friendNumber);
        ToggleButton shareToggle = (ToggleButton) row.findViewById(R.id.shareLocatioToggle);

        friendName.setText(myItems[position]);
        friendNumber.setText("8888888888");
        //friendThumb.setImageResource(R.drawable.friend_dp_thumb);

        shareToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                // TODO Auto-generated method stub
                if (arg1) {
                    Toast.makeText(getApplicationContext(), "Shared with "+myItems[position], Toast.LENGTH_SHORT).show();
                }
            }
        });

        shareToggle.setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View arg0) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "Share your location", Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        return row;
    }



}

谢谢

您必须使用 setter getter 方法维护切换标志,默认情况下它是关闭的,然后您必须 on/off 切换并调用 notifydatasetchanged() 来维护它的状态。

如果视图超出列表视图的可见性,切换状态将重新创建。可以使完整的 activity 可滚动。所以切换按钮不会丢失它的状态

您需要 2 个东西,一个数组来记住哪些项目已被切换,并明确 setChecked() 那些已被切换的项目。

private boolean[] myChecks = new boolean[myItems.length];
private class MyAdapter extends ArrayAdapter<String> {
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ...
        shareToggle.setChecked(myChecks[position]);
        shareToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                ...
                myChecks[position] = arg1;
            }
        });
}