【问题标题】:How to Handle the checkbox ischecked and unchecked event in android如何在android中处理复选框ischecked和unchecked事件
【发布时间】:2021-03-14 07:35:37
【问题描述】:

我是 android 新手。我制作了一个简单的数学应用程序。 我使用复选框选择正确选项,但问题在这里答案选项不仅是一个而且是二,三个意味着多选所以我使用复选框

chkOption.setOnCheckedChangeListener(this);

事件并尝试处理此事件。并将选择值存储在一个 Arraylist 中。但是当我选择选项时,值被添加到 arrayList 但是当我取消选中(Diselect)时,事件也会发生并且值添加到 arraylist . 我的代码在下面

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {   
        CheckBox chk=(CheckBox) buttonView;
        if(chk.isChecked())
        {
            forMetchCheckBox.add(String.valueOf(chk.getText()));            
        }
    }   

forMetchCheckbow 是我的 String ArrayList 。所以我能做什么? 如何处理这个问题。 如果任何用户取消选择该选项,则复选框选择值将从 ArrayList 中删除。可能吗?

【问题讨论】:

  • 你有多少个复选框?

标签: android checkbox


【解决方案1】:

您似乎拥有多个复选框,并且您正在为每个复选框设置全局侦听器。因此,在这种情况下,您还需要识别特定复选框的事件。

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {   
        int id = buttonView.getId();
        if(id == R.id.chk)
        {
          if(chk.isChecked()){
               forMetchCheckBox.add(String.valueOf(chk.getText()));
            }
           else{
               forMetchCheckBox.remove(String.valueOf(chk.getText()));
           }
        }
        else if(id == R.id.chk1){
           ....
        }
    }  

等等,这将使您的听众工作完美。

【讨论】:

  • 是的,我也使用此代码,但我的问题是如何在选择复选框取消选择(未选中)后删除 arraylist 中的添加项
【解决方案2】:

你的 if 条件有什么问题。应该是:

if( isChecked ) 

而不是

if( chk.isChecked() )

【讨论】:

  • 我编辑我的答案..isChecked 是函数参数。我写错了。
  • 但是如何在取消选择(未选中)复选框后删除添加项目。
【解决方案3】:
chk.setOnCheckedChangeListener(new OnCheckedChangeListener() {

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

                      if(isChecked){
                          chetimeslot = (String)chk.getTag();
                            checkbox_timeslot.add(chetimeslot);

                        }
                       else{
                           chetimeslot = (String)chk.getTag();
                            checkbox_timeslot.remove(chetimeslot);


                       }

});

【讨论】:

    【解决方案4】:

    使用 CheckBox 在自定义列表视图中一次选择最多 5 个复选框或计数选中和未选中的复选框

         package com.test;
    
     import java.util.ArrayList;
     import android.app.Activity;
     import android.app.AlertDialog;
     import android.app.ListActivity;
     import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.KeyEvent;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.view.View.OnClickListener;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.widget.AdapterView.OnItemClickListener;
    
    
    public class ListViewCheckboxesActivity extends ListActivity {
    
        AlertDialog alertdialog = null;
        int i1, i2, i3 = 0;
        Country rowcheck;
        MyCustomAdapter dataAdapter = null;
        ListView listView = null;
        int k = 1;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.fmain);
    
            // Generate list View from ArrayList
            displayListView();
            checkButtonClick();
    
        }
    
        private void displayListView() {
    
            // Array list of countries Equipments
            ArrayList<Country> rowcheckList = new ArrayList<Country>();
            Country rowcheck = new Country("", "Hex Bolts", false);
            rowcheckList.add(rowcheck);
            rowcheck = new Country("", "Hex Cap Screw", false);
            rowcheckList.add(rowcheck);
            rowcheck = new Country("", "Round Head Bolt", false);
            rowcheckList.add(rowcheck);
            rowcheck = new Country("", "Slotted Head Hex Bolt", false);
            rowcheckList.add(rowcheck);
            rowcheck = new Country("", "Socket Cap Screw", false);
            rowcheckList.add(rowcheck);
            rowcheck = new Country("", "Sockets", false);
            rowcheckList.add(rowcheck);
            rowcheck = new Country("", "Square Head Bolt", false);
            rowcheckList.add(rowcheck);
            rowcheck = new Country("", "Carriage Bolt", false);
            rowcheckList.add(rowcheck);
            rowcheck = new Country("", "Plow Bolt", false);
            rowcheckList.add(rowcheck);
    
            rowcheck = new Country("", "Struts Clamp", false);
            rowcheckList.add(rowcheck);
    
            listView = getListView();
    
            dataAdapter = new MyCustomAdapter(this, R.layout.rowcheck_info,
                    rowcheckList);
    
            // Assign adapter to ListView
            listView.setAdapter(dataAdapter);
    
            listView.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView parent, View view,
                        int position, long id) {
                    // When clicked, show a toast with the TextView text
                    Country rowcheck = (Country) parent.getItemAtPosition(position);
    
                }
    
            });
    
        }
    
        private class MyCustomAdapter extends ArrayAdapter<Country> {
            private ArrayList<Country> rowcheckList;
    
            public MyCustomAdapter(Context context, int textViewResourceId,
                    ArrayList<Country> rowcheckList) {
                super(context, textViewResourceId, rowcheckList);
                this.rowcheckList = new ArrayList<Country>();
                this.rowcheckList.addAll(rowcheckList);
            }
    
            private class ViewHolder {
                TextView code;
                CheckBox name;
            }
    
            @Override
      public View getView(int position, View convertView, ViewGroup parent) {
    
       ViewHolder holder = null;
       Log.v("ConvertView", String.valueOf(position));
    
       if (convertView == null) 
       {
       LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       convertView = vi.inflate(R.layout.rowcheck_info, null);
    
       holder = new ViewHolder();
       holder.code = (TextView) convertView.findViewById(R.id.code);
       holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
       convertView.setTag(holder);
    
        holder.name.setOnClickListener( new View.OnClickListener()
        { 
         public void onClick(View v) 
         { 
          CheckBox cb = (CheckBox) v ; 
          Country rowcheck = (Country) cb.getTag(); 
    
          //To check maximum 5 Selection
          if(k>5)
          {
    
              if(!cb.isChecked())
              {
    
    
                      rowcheck.selected=true;
                      System.out.println(k--);
    
    
               }
    
              else
              {
                  System.out.println("if block in-----");
                  cb.setChecked(false);
                  Toast.makeText(getApplicationContext(), "Maximum Selection", Toast.LENGTH_LONG).show();
              }
    
    
          }
    
          else
          {
    
              System.out.println("else block in-----");
    
              if(!cb.isChecked())
              {
    
    
                      rowcheck.selected=true;
                      System.out.println(k--);
    
               }
    
    
              else if(cb.isChecked())
              {
    
    
                         rowcheck.selected=false;
                         System.out.println(k++);
    
    
    
              }
    
          }
    
    
    
    
    
         Toast.makeText(getApplicationContext(),
           "Clicked on Checkbox: " + cb.getText() +
           " is " + cb.isChecked(),
           Toast.LENGTH_LONG).show()
           rowcheck.setSelected(cb.isChecked());
         } 
        }); 
       }
       else 
       {
        holder = (ViewHolder) convertView.getTag();
       }
    
       Country rowcheck = rowcheckList.get(position);
      // holder.code.setText(" (" +  rowcheck.getCode() + ")");
       holder.code.setText(rowcheck.getName());
      // holder.name.setText(rowcheck.getName());
       holder.name.setChecked(rowcheck.isSelected());
       holder.name.setTag(rowcheck);
    
       return convertView;
    
      }
        }
    
        private void checkButtonClick() {
    
            Button myButton = (Button) findViewById(R.id.findSelected);
            myButton.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    StringBuffer responseText = new StringBuffer();
                    responseText.append("The following were selected...\n");
    
                    ArrayList<Country> rowcheckList = dataAdapter.rowcheckList;
    
                    System.out.println("Size" + rowcheckList.size());
                    int j = 0;
                    ArrayList<String> stt = new ArrayList<String>();
                    for (int i = 0; i < rowcheckList.size(); i++) {
                        Country rowcheck = rowcheckList.get(i);
                        // System.out.println(rowcheck.getName());
    
                        if (rowcheck.isSelected()) {
                            stt.add(rowcheck.getName());
                            // Country.st=new ArrayList<String>();
                            String s = rowcheck.getName();
                            System.out.println("String--" + rowcheck.getName());
                            Country.st.add(s);
                            j = j++;
                            System.out.println(j++);
    
                            responseText.append("\n" + rowcheck.getName());
    
                        }
    
                    }
                    for (int i = 0; i < stt.size(); i++) {
                        System.out.println("Names----" + stt.get(i).toString());
                    }
    
                    if (j >= 1 && j <= 5) {
    
                        Intent i = new Intent(ListViewCheckboxesActivity.this,
                                PickedItemListView.class);
                        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(i);
                    } else {
                        Toast.makeText(ListViewCheckboxesActivity.this,
                                "Maximum 5 Selection Allowed", Toast.LENGTH_LONG)
                                .show();
                    }
    
                    Toast.makeText(ListViewCheckboxesActivity.this, responseText,
                            Toast.LENGTH_LONG).show();
    
                }
            });
    
        }
    //Logout ALert Box
        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
    
                LayoutInflater inflater = LayoutInflater
                        .from(ListViewCheckboxesActivity.this);
                View dialogview = inflater.inflate(R.layout.logout_popup, null);
                final Button ok = (Button) dialogview.findViewById(R.id.ok);
                final Button cancel = (Button) dialogview.findViewById(R.id.cancel);
                AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(
                        (ListViewCheckboxesActivity.this));
                dialogbuilder.setView(dialogview);
                dialogbuilder.setInverseBackgroundForced(true);
                alertdialog = dialogbuilder.create();
                alertdialog.show();
    
                ok.setOnClickListener(new OnClickListener() {
    
                    public void onClick(View paramView) {
                        alertdialog.dismiss();
                        final Intent intent = new Intent(
                                ListViewCheckboxesActivity.this,
                                LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        finish();
                    }
    
                });
    
                cancel.setOnClickListener(new OnClickListener() {
    
                    public void onClick(View paramView) {
                        alertdialog.cancel();
                    }
                });
    
            }
            return super.onKeyDown(keyCode, event);
        }
    
    }
    

    【讨论】:

      【解决方案5】:
      checkBox_sound.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
              @Override
              public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
      
                  var boolSoundOn = (isChecked) ? true : false;
      
              }
          });
      

      完美运行...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-10
        • 1970-01-01
        • 1970-01-01
        • 2017-03-31
        • 1970-01-01
        • 2011-03-27
        • 1970-01-01
        • 2021-06-16
        相关资源
        最近更新 更多