在Listview中保持复选框状态

时间:2013-06-26 13:27:04

标签: android android-listview android-checkbox

我在listview中保持复选框状态有问题。我已经尝试了很多关于这个问题的stackoverflow问题。但还没找到任何解决方案。请有人帮帮我这是我的自定义适配器中的getView方法。

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);



        View rowView = inflater.inflate(R.layout.row_sub_packages, parent,
                false);

        TextView title = (TextView) rowView.findViewById(R.id.textView1);

        TextView desc = (TextView) rowView.findViewById(R.id.textView2);

        TextView sub = (TextView) rowView.findViewById(R.id.TextView01);
        TextView book = (Button) rowView.findViewById(R.id.button2);

        CheckBox fav = (CheckBox) rowView.findViewById(R.id.check1);

        Flag.clear();
        Flag = dh.getData(6, "packages");

        boolean flag = false;

        for (int i = 0; i < Flag.size(); i++) {

            if (Flag.get(i)
                    .equals(SubPackagesFragment.Sub_cat_Id[position])) {

                Log.i("Flag true", "Flag true " + Flag.get(i) + " "
                        + SubPackagesFragment.Sub_cat_Id[position]);

                flag = true;
            }

            else {
                flag = false;
            }

        }

        if (flag == true) {
            fav.setChecked(true);
        }

        else {
            fav.setChecked(false);
        }

        fav.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub

                if (isChecked == true) {

                    dh.addfav(Title[position], sub_cat_Sub[position],
                            sub_cat_des[position], Images[position],
                            "packages",
                            SubPackagesFragment.Sub_cat_Id[position]);

                    // Toast.makeText(getContext(),
                    // Title[position]+"+"+SubPackagesFragment.Sub_cat_Id[position],
                    // Toast.LENGTH_SHORT).show();

                } else {
                    // Toast.makeText(getContext(), "off",
                    // Toast.LENGTH_SHORT).show();

                    dh.delete(SubPackagesFragment.Sub_cat_Id[position],
                            "packages");

                }

            }
        });


        title.setText(Title[position]);




        return rowView;

}

1 个答案:

答案 0 :(得分:1)

您正在循环ArrayList,问题是当您检测到true时,如果false语句不在最后,您仍将循环并检测true 。因此,请在检测到break;后尝试设置true