Check/Uncheck multiple checkboxes inside TableLayout

时间:2015-08-07 01:31:05

标签: c# android checkbox xamarin xamarin.android

I have a TableLayout; first column of the first TableRow is a CheckBox. The TableLayout and the first TableRow are created in the .axml file. I create and populate the rest of the TableRows in the .cs file. The first column of each programmatically created TableRow is also a CheckBox.

Using the CheckBox in the first TableRow I would like to Check/Uncheck all programmatically created checkboxes.

In a Windows Forms application I would do this by gathering the checkboxes into an array and iterating through the array to set the checked property on each. In my Android app I can't figure out how to do this.

1 个答案:

答案 0 :(得分:1)

您需要遍历TableRows内的所有TableLayout,找到您的复选框并选中/取消选中它们。为此,请为第一个复选框的click事件添加一个侦听器,其执行如下操作:

//Number of TableRows
var count = tableLayout.ChildCount;
//Position of you checkbox inside each TableRow
//TODO: make this a constant outside the listener method
var checkBoxPosition = 0;

for (int i = 0; i < count ; i++) {
    var tableRow = tableLayout.GetChildAt(i) as TableRow;
    if (tableRow != null) {
        var checkBox = tableRow .GetChildAt(checkBoxPosition) as CheckBox;
         if (checkBox != null) {
             //TODO: Use state of the main checkbox here
             checkBox.Checked = true;
         } 
    }
}