CheckBox的作用:可以提供復選
下面是我點擊按鈕查看所選內容的代碼:定義按鈕監聽器,並在onClick方法中調用shoeAlt方法(此方法會在第二塊代碼定義)
1 Button btn=(Button) findViewById(R.id.btn); 2 3 btn.setOnClickListener(new View.OnClickListener() { 4 5 @Override 6 public void onClick(View v) { 7 showAlt(); 8 9 } 10 });
接下來是定義showAlt方法(首先初始化控件,然后用isCheck方法查看,這些控件哪些被選中,如果被選中就用getText和toString方法得到控件的text)
到這里不得不說Toast
Toast給當前視圖顯示一個浮動的顯示塊,它永遠不會獲得焦點,我會在下一篇的博客中詳細解釋Toast
1 protected CheckBox run, sleep, swim, eat, playball; 2 3 protected void showAlt() { 4 run = (CheckBox) findViewById(R.id.run); 5 sleep = (CheckBox) findViewById(R.id.sleep); 6 swim = (CheckBox) findViewById(R.id.swim); 7 eat = (CheckBox) findViewById(R.id.eat); 8 playball = (CheckBox) findViewById(R.id.playball); 9 StringBuffer str = new StringBuffer(); 10 if (run.isChecked()) { 11 str.append(run.getText().toString() + ","); 12 } 13 if (sleep.isChecked()) { 14 str.append(sleep.getText().toString() + ","); 15 } 16 if (swim.isChecked()) { 17 str.append(swim.getText().toString() + ","); 18 } 19 if (eat.isChecked()) { 20 str.append(eat.getText().toString() + ","); 21 } 22 if (playball.isChecked()) { 23 str.append(playball.getText().toString() + ","); 24 } 25 if (str.length() == 0) { 26 Toast.makeText(this, "請選擇您的愛好", 1).show(); 27 } else { 28 String str1 = str.substring(0, str.length() - 1); 29 Toast.makeText(this, "你的愛好是:" + str1, 1).show(); 30 } 31 32 }