Android CheckBox和RadioButton控件

下面给出Demo,直观见到两个控件如何使用



        

        

        

            

            
        
    
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioGroup;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity implements android.widget.RadioGroup.OnCheckedChangeListener{

    private CheckBox cb;
    private RadioGroup rg;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //初始化控件
        cb = (CheckBox) findViewById(R.id.checkBox1);
        rg = (RadioGroup) findViewById(R.id.radioGroup1);
       
       //绑定事件
        cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            //button 被操作的控件,isChecked为  android:checked="true"
            @Override
            public void onCheckedChanged(CompoundButton button, boolean isChecked) {
                if(isChecked){
                    String text = button.getText().toString();
                    Toast.makeText(MainActivity.this, "男", Toast.LENGTH_SHORT).show();
                    Log.i("Tag",text);
                }               
            }
        });     
        rg.setOnCheckedChangeListener(this);
    }
         //radioGroup Radio组,radioId 子控件的ID
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int radioId) {
        switch(radioId){
        case R.id.radioButton1:
            Toast.makeText(this, "男", Toast.LENGTH_SHORT).show();
            break;
        case R.id.radioButton2:
            Toast.makeText(this, "女", Toast.LENGTH_SHORT).show();
            break;
        default :break;
        
        }
        
    }
}

效果图:

Android CheckBox和RadioButton控件_第1张图片
t.gif

你可能感兴趣的:(Android CheckBox和RadioButton控件)