1. 程式人生 > >android studio checkbox複選框的選中,並顯示打印出來

android studio checkbox複選框的選中,並顯示打印出來

package com.example.checkbox;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity {

	private Button mOkBt;
	private CheckBox mSportCb;
	private CheckBox mReadingCb;
	private CheckBox mGameCb;
	private LinearLayout mLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }
    
    private void initViews(){
    	mOkBt =(Button)findViewById(R.id.ok_bt);
    	mSportCb = (CheckBox)findViewById(R.id.sport_cb);
    	mReadingCb = (CheckBox)findViewById(R.id.reading_cb);
    	mGameCb = (CheckBox)findViewById(R.id.game_cb);
    	mLayout = (LinearLayout)findViewById(R.id.layout);
    	
    	mOkBt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				String hobby = "a";//"a"  "xxx"  直接修改String會產生新的String
//				hobby += "xxx";
//				經常對字串進行修改時,推薦使用StringBuffer或者StringBuilder
//				StringBuffer  執行緒安全的 (會降低執行速度)   ,StringBuilder 非執行緒安全的
				StringBuilder hobby = new StringBuilder();
//				if(mSportCb.isChecked()){
//					hobby.append(mSportCb.getText()+" ");
//				}
//				if(mReadingCb.isChecked()){
//					hobby.append(mReadingCb.getText()+" ");
//				}
//				if(mGameCb.isChecked()){
//					hobby.append(mGameCb.getText()+" ");
//				}
//				遍歷所有佈局中的CheckedBox控制元件
//				獲得子控制元件的數量
				int count = mLayout.getChildCount();
				for(int i = 0;i < count;i++){
//					獲得子控制元件物件
					View child = mLayout.getChildAt(i);
//					判斷是否是CheckBox
					if(child instanceof CheckBox){
//						轉為CheckBox物件
						CheckBox cb = (CheckBox)child;
						if(cb.isChecked()){
							hobby.append(cb.getText()+" ");
						}
					}
				}
				if(hobby.length() == 0){
					Toast.makeText(MainActivity.this, "木有愛好", Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(MainActivity.this, "愛好有:"+hobby.toString(), Toast.LENGTH_SHORT).show();
				}
			}
		});
    }

   
    
}
結果如下: