2017-07-19 65 views

回答

0

假设你有一个父LinearLayout,并且它有三个复选框。

创建LinearLayout的引用。

LineaLayout linearLayout = (LinearLayout) findVIewById(R.id.lv); 

然后,CheckBox指出你必须遍历Linearlayout的ChildViews。

喜欢的东西,

for (int i = 0; i < linearLayout.getChildCount(); i++) { 
    View v = linearLayout.getChildAt(i); 
    if (v instanceof CheckBox) { 
     if (((CheckBox) v).isChecked()) 
     // Check Checkbox 
     else 
     // Unchecked Checkbox 
    } 
} 
0

要确定CheckBox被选中,你可以调用myCheckbox.isChecked()。要设置TextView的值,可以拨打myTextView.setText()。当按下Button时,您可以使用myButton.setOnClickListener()添加View.OnClickListener

总之,这意味着你可以创建一个这样的程序:

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     final CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkbox1); 
     final CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkbox2); 
     final CheckBox checkBox3 = (CheckBox) findViewById(R.id.checkbox3); 
     final TextView textView = (TextView) findViewById(R.id.text); 

     Button button = (Button) findViewById(R.id.button); 
     button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       int count = 0; 

       if (checkBox1.isChecked()) { 
        ++count; 
       } 

       if (checkBox2.isChecked()) { 
        ++count; 
       } 

       if (checkBox3.isChecked()) { 
        ++count; 
       } 

       textView.setText("How many checked? " + count); 
      } 
     }); 
    } 
} 
+0

以及如何确定选中哪些复选框? – blackHawk

+0

你是什么意思?代码包括'if(checkBox1.isChecked())'...这就是你如何确定checkBox1是否被选中。 –

0

最好的方法是使用列表视图:

首先创建一个ListView和形成具有在每个复选框自定义适配器行。

在适配器具有Set<Integer> indexes = new HashSet<Integer>()

在getView()方法:getView(INT位置,查看convertView,ViewGroup中亲本)

为复选框分配点击监听:

checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) 
     { 
      if(isChecked){ 
      indexes.add(position); 
      }else{ 
      indexes.remove(position); 
      } 

     } 
    } 
); 

最后只需访问该设置,您将获得设置的长度,即所选复选框的数量,并且这些值代表所选复选框的位置。

相关问题