选中全部或取消选中android中所有动态创建的复选框

时间:2016-01-18 09:21:09

标签: android android-layout checkbox dynamic multidimensional-array

1.我的所有代码。 2.创建动态复选框以选中或取消选中所有复选框
    {final String [] [] itemContainer = new String [30] [7];     TableLayout tblItemDetail;     @覆盖     protected void onCreate(Bundle savedInstanceState){     super.onCreate(savedInstanceState);     的setContentView(R.layout.activity_item_code_release);     tblItemDetail =(TableLayout)findViewById(R.id.tblItemDetail);
    尝试{     sqlItem =“”;     sqlItem =“SELECT * from itm_mst”;     rs = objDbConnect.getResultSet(sqlItem);     if(rs.next()){     int i1 = 1;     做{     itemContainer [ITEMCOUNT] [0] = Integer.toString(I1 ++);     itemContainer [ITEMCOUNT] [6] = “N”; //复选框值     ITEMCOUNT ++;     } while(rs.next());     tblItemDetail.removeAllViews();     if(itemCount> 0){

CheckBox tvchkall = new CheckBox(ItemCodeRelease.this);  //header row checkbox for ckeck or uncheck all checkbox
tvchkall.setGravity(Gravity.CENTER);
tvchkall.setPadding(20, 0, 20, 0);
tvchkall.setText("Y");
headerRow1.addView(tvchkall);
tvchkall.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(buttonView.isChecked())
 {                              
 for(int a = 0 ; a < itemContainer.length ; a++)
 {
   for(int b = 0 ; b < itemContainer[a].length ; b++)
    {
       CheckBox chkb = (CheckBox)tblItemDetail.findViewById(a);
       if ( chkb == null )
       continue;
       chkb.setChecked(true);
   Log.i("Checkbox serrch","checked  "+chkb.getText()+"ID +chkb.getId());
   if(a == chkb.getId())
    {
      itemContainer[a][6] = "Y";
    }
      else
    {
     Log.i("Checkbox serrch","unchecked"+chkb.getText()+"ID  "+chkb.getId());
    itemContainer[a][6] = "N";
     }}}}
     });
     tblItemDetail.addView(headerRow1);
     int alternateRow1 = 0;
      for (i = 0; i < itemCount; i++) {
       TableRow bodyRow1 = new TableRow(ItemCodeRelease.this);
       if (alternateRow1 % 2 == 0) {
          bodyRow1.setBackgroundResource(R.color.statusalternateRow);
      }
      else {
      bodyRow1.setBackgroundResource(R.color.statusRow);
          }
      final CheckBox cb1 = new CheckBox(ItemCodeRelease.this);   //body row of checkbox
      cb1.setId(i);
      cb1.setGravity(Gravity.CENTER);
       cb1.setPadding(20, 0, 20, 0);
      bodyRow1.addView(cb1);
      cb1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
       @Override
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
          // TODO Auto-generated method stub
         for(int a = 0 ; a < itemContainer.length ; a++)
            {
             for(int b = 0 ; b < itemContainer[a].length ; b++)
              {
                   if(buttonView.isChecked())
                   {
                     Log.i("Checkbox serrch","checked  "+buttonView.getText()+"ID  "+buttonView.getId());
                    if(a == buttonView.getId())
                    {
                        itemContainer[a][6] = "Y";
                          continue;
                     }}
                     else
                    {
                       itemContainer[a][6] = "N";
                      }}}}
                     });
                     bodyRow1.addView(tvBodySRNo1);
                     tblItemDetail.addView(bodyRow1);       
                     alternateRow1++;
               }}} 
               } catch (Exception e) {      e.printStackTrace();                      }}

2 个答案:

答案 0 :(得分:0)

更新[26-01-2016]:您可以按照此方式检查/取消选中动态创建的复选框。

在onCreate(Bundle bundle){...}里面添加: 几点注意事项:

  1. 如果您使用以下内容,则需要为基本布局提供ID:

    setContentView(R.layout.new_layout);
    

    也就是说,当您使用layout xml设置ContentView时。

  2. 您可能需要在值文件夹中的ids.xml中创建虚拟ID以实现可用性。
  3. 请记住,您可以为动态创建的布局应用类似的逻辑,而不是使用布局xml。
  4. 请记住,您可以为其他复合按钮而不是CheckBox使用类似的逻辑。

    //Get Base Layout
    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.base_layout);
    
    //Create new CheckBox
    CheckBox mainCheckBox = new CheckBox(this);
    //Create a new ids.xml in values folder and add dummy id there. Than use that dummy id for dynamically created views
    mainCheckBox.setId(R.id.main_cb);
    //Give a name to it
    mainCheckBox.setText(R.string.mainCB);
    //Add it to Base layout
    linearLayout.addView(mainCheckBox, 0);
    
    //Create other CheckBoxes...
    CheckBox[] checkBoxes = new CheckBox[5];
    for (int i = 0; i < 5; i++) {
        checkBoxes[i] = new CheckBox(this);
        checkBoxes[i].setText(String.format(Locale.getDefault(), "Child CheckBox %d", i + 1));
        checkBoxes[i].setId(i+101);
        linearLayout.addView(checkBoxes[i], i+1);
    }
    
    //Creating each checkbox individually:
    CheckBox checkBox = new CheckBox(this);
    checkBox.setText("Child CheckBox 6");
    //Either add an integer value
    checkBox.setId(106);
    /*
    * Or else use a dummy id
    * checkBox.setId(R.id.child_cb);
    */
    linearLayout.addView(checkBox, 6);
    
    //Set listener to main CheckBox
    mainCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            //Create an array of integer type to store all ids of child CBs
            int[] ids = new int[] { 101, 102, 103, 104, 105, 106 };
                /*
                 * You can also do
                 * int[] ids = new int[] { 101, 102, 103, 104, 105, R.id.child_cb };
                 */
            if(isChecked) {
                Toast.makeText(getBaseContext(), "Checked", Toast.LENGTH_SHORT).show();
                checkChildCBs(ids);
            } else {
                Toast.makeText(getBaseContext(), "Unchecked", Toast.LENGTH_SHORT).show();
                unCheckChildCBs(ids);
            }
        }
    });
    
  5. 检查所有CheckBoxes的方法

        private void checkChildCBs(int[] ids) {
            //Create CheckBox array of same size as that of ids
            CheckBox[] checkBoxes = new CheckBox[ids.length];
            //Run loop to check them
            for (int i = 0; i < ids.length; i++) {
                checkBoxes[i] = (CheckBox) findViewById(ids[i]);
                checkBoxes[i].setChecked(true);
            }
        }
    

    取消检查所有CheckBox的方法

        private void unCheckChildCBs(int[] ids) {
            //Create CheckBox array of same size as that of ids
            CheckBox[] checkBoxes = new CheckBox[ids.length];
            //Run loop to unCheck them
            for (int i = 0; i < ids.length; i++) {
                checkBoxes[i] = (CheckBox) findViewById(ids[i]);
                checkBoxes[i].setChecked(false);
            }
        }
    

    /res/values/ids.xml:

        <?xml version="1.0" encoding="utf-8"?>
        <resources>
            <item type="id" name="main_cb" />
            <item type="id" name="child_cb" />
        </resources>
    

    更新:您可以按照以下代码启用/禁用动态创建的CheckBoxPreferences。

    在/ res / xml / directory中创建一个名为preferences.xml的新文件:

    <?xml version="1.0" encoding="utf-8"?>
    <PreferenceScreen 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:key="pref_screen">
    </PreferenceScreen>
    

    比onCreate()中的PreferenceActivity:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Add preference xml file from /res/xml/
        addPreferencesFromResource(R.xml.preferences);
    }
    

    现在我们将动态创建CheckBoxPreference:

    // Get PreferenceScreen using the key as stated in preferences.xml
    PreferenceScreen prefScreen = (PreferenceScreen) findPreference("pref_screen");
    
    // Now create a CheckBoxPreference array. The size of the array will be the number of required CheckBoxPreferences.
    CheckBoxPreference[] cbPrefs = new CheckBoxPreference[5]; // You can set any number you want. This will allow you to create 5 CheckBoxPreferences.
    
    // Run loop to create CheckBoxPreferences and add them to the PreferenceScreen.
    for (int  i = 0; i < cbPrefs.length; i++) {
        cbPrefs[i] = new CheckBoxPreference(getActivity());
        cbPrefs[i].setTitle("Dynamically created multiple Pref " + (i+1));
        cbPrefs[i].setKey("multiple_dynamic_pref_key_" + (i+1));
        prefScreen.addPreference(cbPrefs[i]); // Adds the newly created CheckBoxPreference to the PreferenceScreen
    }
    /*
     IF you want, you can also create new CheckBoxPreference individually like this :
     cbPrefs[0] = new CheckBoxPreference(getActivity());
     cbPrefs[0].setTitle("My Preference");
     cbPrefs[0].setKey("my_pref_key");
     prefScreen.addPreference(cbPrefs[0]);
     cbPrefs[1] = new CheckBoxPreference(getActivity());
     cbPrefs[1].setTitle("Some Name");
     cbPrefs[1].setKey("some_pref_key");
     prefScreen.addPreference(cbPrefs[1]);
     and so on and so forth...
    */
    
    // Now create and add a Preference to the PreferenceScreen
    Preference preference = new Preference(getActivity());
    preference.setTitle("Preference");
    prefScreen.addPreference(preference);
    
    // Now set onPreferenceClickListener to newly created preference.
    preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            String[] prefKeys = new String[] {"multiple_dynamic_pref_key_1", "multiple_dynamic_pref_key_2", 
            "multiple_dynamic_pref_key_3", "multiple_dynamic_pref_key_4", 
            "multiple_dynamic_pref_key_5"};
            changePrefsState(prefKeys, cbPrefs);
            return false;
        }
    });
    

    最后你的onCreate()将如下所示:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Add preference xml file from /res/xml/
        addPreferencesFromResource(R.xml.preferences);
    
        // Get PreferenceScreen using the key as stated in preferences.xml
        PreferenceScreen prefScreen = (PreferenceScreen) findPreference("pref_screen");
    
        // Now create a CheckBoxPreference array. The size of the array will be the number of required CheckBoxPreferences.
        CheckBoxPreference[] cbPrefs = new CheckBoxPreference[5]; // You can set any number you want. This will allow you to create 5 CheckBoxPreferences.
    
        // Run loop to create CheckBoxPreferences and add them to the PreferenceScreen.
        for (int  i = 0; i < cbPrefs.length; i++) {
            cbPrefs[i] = new CheckBoxPreference(getActivity());
            cbPrefs[i].setTitle("Dynamically created multiple Pref " + (i+1));
            cbPrefs[i].setKey("multiple_dynamic_pref_key_" + (i+1));
            prefScreen.addPreference(cbPrefs[i]); // Adds the newly created CheckBoxPreference to the PreferenceScreen
        }
    
        // Now create and add a Preference to the PreferenceScreen
        Preference preference = new Preference(getActivity());
        preference.setTitle("Preference");
        PreferenceScreen.addPreference(preference);
    
        // Now set onPreferenceClickListener to newly created preference.
        preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                String[] prefKeys = new String[] {"multiple_dynamic_pref_key_1", "multiple_dynamic_pref_key_2", 
                "multiple_dynamic_pref_key_3", "multiple_dynamic_pref_key_4", 
                "multiple_dynamic_pref_key_5"};
                changePrefsState(prefKeys, cbPrefs);
                return false;
            }
        });
    }
    
    // This function is called when you click on preference to check/uncheck CheckBoxPrefs.
    private void changePrefsState(String[] prefKeys, CheckBoxPreference[] checkBoxPreferences) {
        try {
            for (int i = 0; i < prefKeys.length; i++) {
                checkBoxPreferences[i] = (CheckBoxPreference) findPreference(prefKeys[i]);
                // Check if CheckBozPreference is Checked. If yes than unCheck it else Check it
                if (checkBoxPreferences[i].isChecked())
                    checkBoxPreferences[i].setChecked(false);
                else
                    checkBoxPreferences[i].setChecked(true);
            }
        } catch(Exception e) {
            Toast.makeText(getActivity().getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    

    旧:

        private void someFunction() {    
            String[] prefKeys = new String[] {"pref_key_1", "pref_key_2", "pref_key_3", "pref_key_4", "pref_key_5"};
            CheckBoxPreference[] cbPrefs = new CheckBoxPreference[prefKeys.length];
            changePrefsState(prefKeys, cbPrefs);
        }
    
        private void changePrefsState(String[] prefKeys, CheckBoxPreference[] checkBoxPreferences) {
            try {
                for (int i = 0; i < prefKeys.length; i++) {
                    checkBoxPreferences[i] = (CheckBoxPreference) findPreference(prefKeys[i]);
                    // Check if CheckBozPreference is Checked. If yes than unCheck it else Check it
                    if (checkBoxPreferences[i].isChecked())
                        checkBoxPreferences[i].setChecked(false);
                    else
                        checkBoxPreferences[i].setChecked(true);
                }
            } catch(Exception e) {
                Toast.makeText(getActivity().getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    

    以上示例适用于动态创建的首选项和XML定义的首选项。 你只需要传递密钥和pref类型。 您可以为不同的首选项类型创建不同的changePrefsState(arg1,arg2){...}。

答案 1 :(得分:0)

主复选框,用于选中全部复选框。

  CheckBox tvchkall = new CheckBox(ItemCodeRelease.this);
  tvchkall.setId(101);
  tvchkall.setOnClickListener(getOnClickDoSomething(tvchkall));

listner,检查所有复选框是动态创建者。

View.OnClickListener getOnClickDoSomething(final CheckBox chk) {
    return new View.OnClickListener() {
        public void onClick(View v) {       

            if (chk.getId() == 101) {
                if (chk.isChecked()) {
                    for (int a = 1; a < tblItemDetail.getChildCount(); a++) {
                        itemContainer[a][6] = "Y";                      
                        CheckBox cb1 = (CheckBox) ((TableRow) tblItemDetail.getChildAt(a)).getChildAt(1);
                        cb1.setChecked(true);
                    }
                } else {
                    for (int a = 1; a < tblItemDetail.getChildCount(); a++) {
                        itemContainer[a][6] = "N";                          
                        CheckBox cb11 = (CheckBox) ((TableRow) tblItemDetail.getChildAt(a)).getChildAt(1);
                    }
                }
            } else {
                if (chk.isChecked()) {
                    for (int a = 0; a < itemContainer.length; a++) {
                        for (int b = 0; b < itemContainer[a].length; b++) {
                            if (a == chk.getId()) {
                                itemContainer[a][6] = "Y";                                  
                            }
                        }
                    }
                } else {
                    for (int a = 0; a < itemContainer.length; a++) {
                        for (int b = 0; b < itemContainer[a].length; b++) {
                            if (a == chk.getId()) {
                                itemContainer[a][6] = "N";                                  
                            }                               
                        }
                    }
                }
            }

        }
    };
}