在 Android 中执行“全部标记为”复选框



我正在做一个有很多活动和类的安卓项目。

在一些布局中,我有一个工具,用户可以在其中选择全部标记,以便选中所有复选框。

但是,我面临的问题是我只知道一种方法(太长了(来做到这一点 - 通过为每个现有布局创建一个 markall 布局,将原始布局代码粘贴到 markall 布局代码中,然后给出所有复选框为选中。这要求我也为每个布局的所有取消标记创建 xmls。

请告诉我一种方法,我可以为markall创建一个具有所有选中复选框的xml,然后在单击"全部标记"时在原始布局之上调用该布局。

假设您有以下布局

<LinearLayout
   android:id="@+id/checkbox_container"
   ...params>
   <CheckBox ...params/>
   <TextView ...params/>
   <CheckBox ...params/>
   <SomeView ...params/>
   <CheckBox ...params/>
</LinearLayout>

在"活动"中获取像这样的复选框布局

LinearLayout container = (LinearLayout)findViewById(R.id.checkbox_container);

像这样迭代容器内的子项:

for (int i = 0; i < container.getChildCount(); i++){
    View v = container.getChildAt(i);
    if (v instanceof CheckBox){
        CheckBox cb = (CheckBox)v;
        // isChecked should be a boolean indicating if every Checkbox should be checked or not
        cb.setChecked(isChecked)
    }
}
CheckBox MarkAllCheckBox =
    (CheckBox) findViewById( R.id.MarkAllCheckBox);
MarkAllCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if ( isChecked )
        {
            checkBox1.setChecked("true");
            checkBox2.setChecked("true");
            checkBox3.setChecked("true");
            //so on
        }
    }
});

最新更新