【问题标题】:CheckBox checked automatically in ListViewCheckBox 在 ListView 中自动选中
【发布时间】:2014-06-30 17:33:33
【问题描述】:

当记录超过 5 条时似乎有问题 显示在管理实践上。例如如果有 6 条记录要显示 管理实践。如果我选中第 1 号复选框,第 6 号复选框也 被检查。如果有 7 条记录,并且如果我检查第二条记录,那么 第 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();
}

}

【问题讨论】:

标签: android listview checkbox


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        在您的getView() 中添加:

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

        【讨论】:

        • 但是当取消选中时,我滚动列表视图复选框会自动取消选中
        • 如果您在 SelectedBox 中保持正确的状态,它们不会。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-19
        • 2013-07-25
        • 1970-01-01
        • 1970-01-01
        • 2014-02-04
        • 2012-08-13
        • 1970-01-01
        相关资源
        最近更新 更多