CheckView状态不在Listview中维护

时间:2014-07-12 06:09:13

标签: android checkbox android-listview

  

我正在设置复选框以删除多个项目。当我选中元素时,我的添加按钮会发生变化   要删除,但是当我滚动列表视图时,我的删除按钮更改为添加按钮,但它不应该被解除,直到所有复选框都未选中。保持删除并在操作栏中添加按钮我在使用列表框时单击“检查我”将元素的当前位置设置为复选框,取消选中复选框时,从复选框中删除该位置。

     

我的问题是,当选中复选框时,添加符号会更改为   删除图标。当我滚动并且检查的记录不在屏幕上时,   删除图标更改以添加图标,当我滚动回选中   记录,删除图标返回。我对Listview中的这个复选框非常困惑。请检查我的代码帮助我。

     

提前致谢

package com.office.sdpa.custom.classes;

  

公共类ManagePracAdapter扩展了ArrayAdapter {

private final List<Model> list;
private final Activity context;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
List<Integer> SelectedBox= new ArrayList<Integer>();
MenuItem Delete,addlog;



public ManagePracAdapter(Activity context, List<Model> list,MenuItem mymenu,MenuItem      myaddlog) {
    super(context, R.layout.row, list);
    this.context = context;
    this.list = list;
    Delete=mymenu;
    addlog=myaddlog;

}

static class ViewHolder {
    protected TextView text;
    protected TextView datetime;
    protected TextView weather;
    protected TextView duration;
    protected TextView supervisor;
    protected  TextView day_night_icon;
    protected CheckBox checkbox;

}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    ViewHolder viewHolder = null;
    if (convertView == null) {
        LayoutInflater inflator = context.getLayoutInflater();
        convertView = inflator.inflate(R.layout.logitem1, null);
        viewHolder = new ViewHolder();
        viewHolder.text = (TextView) convertView.findViewById(R.id.id_skills);
        viewHolder.datetime = (TextView) convertView.findViewById(R.id.id_datetime);
        viewHolder.weather = (TextView) convertView.findViewById(R.id.id_weather);
        viewHolder.duration=(TextView)  convertView.findViewById(R.id.totminutes);
        viewHolder.supervisor=(TextView)  convertView.findViewById(R.id.conditions);
        viewHolder.day_night_icon=(TextView)  convertView.findViewById(R.id.day_night_icon);
        viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.id_chkDelete);
        viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.

                if(SelectedBox.size()-1==0)
                {
                    Delete.setVisible(false);
                    addlog.setVisible(true);
                }else
                {
                    addlog.setVisible(false);
                }


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


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

                }
            }
        });





        convertView.setTag(viewHolder);
        convertView.setTag(R.id.id_skills, viewHolder.text);
        convertView.setTag(R.id.id_chkDelete, viewHolder.checkbox);
        convertView.setTag(R.id.id_datetime,viewHolder.datetime);
        convertView.setTag(R.id.id_weather,viewHolder.weather);
        convertView.setTag(R.id.totminutes,viewHolder.duration);
        convertView.setTag(R.id.conditions,viewHolder.supervisor);
        convertView.setTag(R.id.day_night_icon,viewHolder.day_night_icon);

        } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    viewHolder.checkbox.setTag(position); // This line is important.

    viewHolder.text.setText(list.get(position).getName());
    viewHolder.datetime.setText(list.get(position).getDatetime());
    viewHolder.weather.setText(list.get(position).getWeather());
    viewHolder.checkbox.setChecked(list.get(position).isSelected());
    if(!list.get(position).getDay_minutes().toString().equalsIgnoreCase("0"))
    {
        viewHolder.duration.setText(list.get(position).getDay_minutes());
        viewHolder.day_night_icon.setBackgroundResource(R.drawable.sun);
    }else
    {
        viewHolder.duration.setText(list.get(position).getNight_minutes());
        viewHolder.day_night_icon.setBackgroundResource(R.drawable.moon);

    }
    if(list.get(position).getSupervisor().equals("No supervisor"))
    {
        viewHolder.supervisor.setBackgroundResource(R.drawable.pending);
    }else
    {
        viewHolder.supervisor.setBackgroundResource(R.drawable.approve);
    }
    String fontPath = "fonts/Roboto-Light.ttf";
    Typeface tf = Typeface.createFromAsset(context.getAssets(), fontPath);
    viewHolder.datetime.setTypeface(tf);
    viewHolder.duration.setTypeface(tf);
    viewHolder.text.setTypeface(tf);
    viewHolder.weather.setTypeface(tf);


    Delete.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[]=list.get(i).getDatetime().split("  ");

                                Log.d("Checked Element",str[0]+"\n"+str[1]+"\n"+list.get(i).getName());


                                db.DeleteSingleLog(list.get(i).getName(),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) {
            // TODO Auto-generated method stub




            String str1 = null;
            String str[]=list.get(position).getDatetime().split("  ");


            Log.d("PARTICULAR SKILLLLL",str[1]);
            str1=str[0]+"~"+list.get(position).getName()+"~"+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;
}

}

2 个答案:

答案 0 :(得分:0)

尝试更换适配器getView()。

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            convertView = inflator.inflate(R.layout.logitem1, null);
            viewHolder = new ViewHolder();
            viewHolder.text = (TextView) convertView.findViewById(R.id.id_skills);
            viewHolder.datetime = (TextView) convertView.findViewById(R.id.id_datetime);
            viewHolder.weather = (TextView) convertView.findViewById(R.id.id_weather);
            viewHolder.duration=(TextView)  convertView.findViewById(R.id.totminutes);
            viewHolder.supervisor=(TextView)  convertView.findViewById(R.id.conditions);
            viewHolder.day_night_icon=(TextView)  convertView.findViewById(R.id.day_night_icon);
            viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.id_chkDelete);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.text.setText(list.get(position).getName());
        viewHolder.datetime.setText(list.get(position).getDatetime());
        viewHolder.weather.setText(list.get(position).getWeather());
        viewHolder.checkbox.setChecked(list.get(position).isSelected());
        if(!list.get(position).getDay_minutes().toString().equalsIgnoreCase("0"))
        {
            viewHolder.duration.setText(list.get(position).getDay_minutes());
            viewHolder.day_night_icon.setBackgroundResource(R.drawable.sun);
        }else
        {
            viewHolder.duration.setText(list.get(position).getNight_minutes());
            viewHolder.day_night_icon.setBackgroundResource(R.drawable.moon);

        }
        if(list.get(position).getSupervisor().equals("No supervisor"))
        {
            viewHolder.supervisor.setBackgroundResource(R.drawable.pending);
        }else
        {
            viewHolder.supervisor.setBackgroundResource(R.drawable.approve);
        }
        String fontPath = "fonts/Roboto-Light.ttf";
        Typeface tf = Typeface.createFromAsset(context.getAssets(), fontPath);
        viewHolder.datetime.setTypeface(tf);
        viewHolder.duration.setTypeface(tf);
        viewHolder.text.setTypeface(tf);
        viewHolder.weather.setTypeface(tf);

        viewHolder.checkbox.setTag(position); // This line is important.


        viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                list.get(position).setSelected(isChecked); // Set the value of checkbox to maintain its state.

                if(SelectedBox.size()-1==0)
                {
                    Delete.setVisible(false);
                    addlog.setVisible(true);
                }else
                {
                    addlog.setVisible(false);
                }


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


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

                }
            }
        });

        Delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                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[]=list.get(i).getDatetime().split("  ");

                                            Log.d("Checked Element",str[0]+"\n"+str[1]+"\n"+list.get(i).getName());


                                            db.DeleteSingleLog(list.get(i).getName(),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) {
                // TODO Auto-generated method stub




                String str1 = null;
                String str[]=list.get(position).getDatetime().split("  ");


                Log.d("PARTICULAR SKILLLLL", str[1]);
                str1=str[0]+"~"+list.get(position).getName()+"~"+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;
    }

答案 1 :(得分:0)

尝试按如下方式制作getView方法:

public class ViewHolder
{
    TextView contactname, statusmsg, msisdnview, imgview, chatstsview;
    ImageView img;
    CheckBox contactCheckBox;
}
ViewHolder holder = null;
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
    // TODO Auto-generated method stub
    holder=new ViewHolder();
    View rowView = convertView;  
    if(rowView == null)
    {
        rowView = inflater.inflate(R.layout.contact_list, null);
        holder.contactname=(TextView) rowView.findViewById(R.id.textView1);
        holder.statusmsg=(TextView) rowView.findViewById(R.id.textView2);
        holder.img=(ImageView) rowView.findViewById(R.id.imageView1); 
        holder.contactCheckBox = (CheckBox) rowView.findViewById(R.id.contactchk);
        rowView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) rowView.getTag();
    }

    holder.contactname.setTag("textview_"+msisdn[position]);
    holder.contactCheckBox.setTag("checkbox_"+msisdn[position]);
    holder.contactname.setText(result[position]);

    ImageLoader img = new ImageLoader(context);
    img.DisplayImage(imageId[position], loader, holder.img);

    holder.statusmsg.setText(status[position]);

    holder.contactCheckBox.setTag(position);

    holder.contactCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {           
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            // TODO Auto-generated method stub
            int getPosition = (Integer) buttonView.getTag();
            isCheckedCheckBox[getPosition] = buttonView.isChecked();
        }
    });


    if(isCheckedCheckBox[position])
    {
        holder.contactCheckBox.setChecked(true);
    }  
    else
    {
       holder.contactCheckBox.setChecked(false);
    }
    holder.contactCheckBox.setOnClickListener(null);

    rowView.setTag(holder);
    return rowView;
}

这可以解决您的问题。