简体   繁体   中英

CheckBox checked automatically in ListView

There seems to be a problem when there are more than 5 records to display on Manage Practice. For eg if there are 6 records to display on Manage Practice. If I check the check box number 1, the check box number 6 also gets checked. If there are 7 records, and if I check on 2nd record, then the 7th record also gets automatically checked.I don't what's going on there I am very confusing, Please check my code let me know what's problem is there.

    public class ManagePracticeLogAdapter extends BaseAdapter

{

//Variables to save class  object.
Context context;

// variable to instantiates a layout XML file into its corresponding View objects.
LayoutInflater inflater;

MenuItem menu,addlog;


List<Integer> SelectedBox= new ArrayList<Integer>();;

// Variable to accept list data from Produce log  activity
ArrayList<HashMap<String, String>> data;

ArrayList<HashMap<String, String>> temp_data;
HashMap<String, String> resultp = new HashMap<String, String>();


List<String> deleteData=new ArrayList<String>();

// Constructor to accept class instance and data.   
public ManagePracticeLogAdapter(Context context,
        ArrayList<HashMap<String, String>> arraylist,MenuItem mymenu,MenuItem myaddlog)
{
    this.context = context;
    data = arraylist;
    //temp_data.addAll(data);
    menu=mymenu;
    addlog=myaddlog;
}

@Override
public int getCount() 
{
    return data.size();
}

@Override
public Object getItem(int position) 
{
    return null;
}

@Override
public long getItemId(int position)
{
    return 0;
}

// Method  to display data of Produce log Activity in list view 
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
    if(convertView==null)
    {


        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        convertView= inflater.inflate(R.layout.logitem1, parent, false);
    }
    TextView datetime;
    TextView totminutes;
    TextView skills;
    TextView weather;
    TextView day_night_icon;
    final CheckBox chkdelete;
    TextView approval_icon;


    // Get the position
    resultp = data.get(position);

    // Locate the TextViews in listview_item.xml
    datetime = (TextView) convertView.findViewById(R.id.id_datetime);
    totminutes = (TextView) convertView.findViewById(R.id.totminutes);
    skills= (TextView) convertView.findViewById(R.id.id_skills);
    weather=(TextView)convertView.findViewById(R.id.id_weather);
    day_night_icon=(TextView)convertView.findViewById(R.id.day_night_icon);
    approval_icon=(TextView)convertView.findViewById(R.id.conditions);
    chkdelete=(CheckBox)convertView.findViewById(R.id.id_chkDelete);

    // Capture position and set results to the TextViews
    datetime.setText(resultp.get("date_time"));

    if(!resultp.get("Day_minutes").toString().equalsIgnoreCase("0"))
    {
        totminutes.setText(resultp.get("Day_minutes")+" min");
        day_night_icon.setBackgroundResource(R.drawable.sun);
    }else
    {
        totminutes.setText(resultp.get("Night_minutes")+" min");
        day_night_icon.setBackgroundResource(R.drawable.moon);
    }

    skills.setText(resultp.get("Skill"));
    weather.setText(resultp.get("weather"));

    String supervisorText=resultp.get("super");

     Log.w("SUPERVISOR", supervisorText);

    if(supervisorText.equals("No supervisor"))
    {
        approval_icon.setBackgroundResource(R.drawable.pending);
    }else
    {
        approval_icon.setBackgroundResource(R.drawable.approve);
    }

    String fontPath = "fonts/Roboto-Light.ttf";
    Typeface tf = Typeface.createFromAsset(context.getAssets(), fontPath);
    datetime.setTypeface(tf);
    totminutes.setTypeface(tf);
    skills.setTypeface(tf);
    weather.setTypeface(tf);



//  chkdelete.setTag(R.id.id_chkDelete);
    chkdelete.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
        {
            // int checkBoxId = (Integer) buttonView.getTag();
            if(SelectedBox.size()-1==0)
            {
                menu.setVisible(false);
                addlog.setVisible(true);
            }else
            {
                addlog.setVisible(false);
            }


            if(isChecked)
            {
                SelectedBox.add(position);
                menu.setVisible(true);
                addlog.setVisible(false);


            }else /*if(!isChecked)*/
            {
            SelectedBox.remove(SelectedBox.indexOf(position));

            }

        }
    });



    menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            // TODO Auto-generated method stub

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

            // set title
            alertDialogBuilder.setTitle("Student Driving Practice Log");

            // set dialog message
            alertDialogBuilder
            .setMessage("Are you sure want to Delete Record!")
            .setCancelable(false)
            .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {

                    try
                    {
                        NewNewDataHelper db=new NewNewDataHelper(context);

                        if(!SelectedBox.isEmpty())
                        {
                            for(int i=0;i<SelectedBox.size();i++)
                            {

                                resultp=data.get(SelectedBox.get(i));
                                String str[]=resultp.get("date_time").split("  ");

                                Log.d("Checked Element",str[0]+"\n"+str[1]+"\n"+resultp.get("Skill"));


                                db.DeleteSingleLog(resultp.get("Skill"),str[0],str[1]);

                                /*resultp=data.get(SelectedBox.get(i));

                                String str[]=resultp.get("date_time").split(" ");
                                db.DeleteSingleLog(resultp.get("Skill"),str[0],str[1]);*/

                                    Toast.makeText(context,"Record Deleted", Toast.LENGTH_LONG).show();


                            }

                            Log.d("LISTSTSTSTST", SelectedBox.toString());


                            Intent intent = new Intent(context,ManagePracticeLogActivity.class);
                            intent.putExtra("s11", "delete");
                            context.startActivity(intent);
                        }
                    }catch(Exception e)
                    {

                    }


                }
            })
            .setNegativeButton("No",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();

                }
            });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();



            return false;
        }
    });



    convertView.setOnClickListener(new OnClickListener() 
    {

        @Override
        public void onClick(View arg0)
        {
            resultp = data.get(position);

            String str1 = null;
            String str[]=resultp.get("date_time").toString().split("  ");

            str1=str[0]+"~"+resultp.get("Skill")+"~"+str[1];
            Log.d("PARTICULAR SKILLLLL", str1);
                Intent intent = new Intent(context,LogEdit.class);
                intent.putExtra("s11","Update Practice");
                intent.putExtra("dataupdate",str1);
                context.startActivity(intent);

        }
    });
    return convertView;
}

private void deleteItems(List<Integer> list)
{
    data.clear();
}

}

just have a look at this . This will explain the "problem" with checkboxes in listviews. There's also a link with a solution, if needed :)

When you load the view in getView, you need to set the check state for that particular item. I assume for each row you store this information somewhere? Just retrieve the correct state for the row (position) and set the correct state on the checkbox. The reason why you are seeing the behavior is because in a ListView rows are reused. The 6th row is in fact the 1st row. It is done this way to conserve memory and optimize a ListView for speed.

Inside your getView() add :

if(SelectedBox.contains(new Integer(position))) {
    chkdelete.setChecked(true);
} else {
    chkdelete.setChecked(false);
}

The problem is, view gets recycled due to recycling of ListView and the value of Checkbox(check or uncheck) is not maintained. You can check this link.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM