2017-07-19 66 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); 
      } 

     } 
    } 
); 

最後只需訪問該設置,您將獲得設置的長度,即所選複選框的數量,並且這些值代表所選複選框的位置。

相關問題