CheckBox在ListView中自动检查

时间:2014-06-30 09:15:53

标签: android listview checkbox

当记录超过5条时似乎存在问题 在管理实践中显示。对于例如如果要显示6条记录 管理实践。如果我选中复选框编号1,则复选框编号为6 得到检查。如果有7条记录,如果我查看第2条记录,那么 第7条记录也会自动检查。我不知道那里发生什么事我很困惑,请检查我的代码让我知道那里有什么问题。

  

    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();
}

}

4 个答案:

答案 0 :(得分:0)

看看this。这将解释listviews中复选框的“问题”。如果需要,还有一个解决方案链接:)

答案 1 :(得分:0)

在getView中加载视图时,需要为该特定项设置检查状态。我假设您在每一行都将此信息存储在某处?只需检索行(位置)的正确状态,并在复选框上设置正确的状态。您看到该行为的原因是因为在ListView行中重用了这些行。第6行实际上是第1行。这样做是为了节省内存并优化ListView以提高速度。

答案 2 :(得分:0)

getView()添加内容

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

答案 3 :(得分:0)

问题是,由于ListView的回收而导致视图被回收,并且不维护Checkbox(检查或取消选中)的值。您可以查看this链接。