1

我从两天开始就一直在尝试解决这个问题。我已经看到很多与此问题相关的问题。但它们对我不起作用。
我有一个习惯ListView。它的每一行包括一个ImageView,两个TextViews和一个ToggleButton。这些都很好。当我将状态更改为ToggleButtontotrue时,当我向下滚动并再次向上滚动时,就会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;
    }



}

谢谢

4

3 回答 3

3

您需要两件事,一个数组来记住哪些项目已被切换,以及明确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;
            }
        });
}
于 2015-02-26T04:57:51.873 回答
0

您必须使用 setter getter 方法维护切换标志,默认情况下它被设置为关闭,然后您必须打开/关闭切换并调用 notifydatasetchanged() 以维护其状态。

于 2015-02-26T04:25:08.207 回答
0

如果视图不在列表视图的可见性范围内,则会重新创建切换状态。可以使整个活动可滚动。所以切换按钮不会丢失其状态

于 2015-02-26T04:54:15.667 回答