android中控件RadioButton的使用

来源:互联网 发布:阿里云 物联网 收入 编辑:程序博客网 时间:2024/04/29 11:57

在layout的activity_main.xml中 



    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="请选择国籍:" />


    <RadioGroup
        android:id="@+id/rg"
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >


        <RadioButton
            android:id="@+id/china"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="中国" />


        <RadioButton
            android:id="@+id/america"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="美国" />


        <RadioButton
            android:id="@+id/japan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="日本" />
    </RadioGroup>


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="查看" >
    </Button>


MainActivity.java

private RadioGroup rg ;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);rg = (RadioGroup) findViewById(R.id.rg) ;rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {//希望弹出来选中项的文本RadioButton rb = (RadioButton) findViewById(checkedId) ;Toast.makeText(MainActivity.this, rb.getText(), 0).show() ;}}) ;}public void click(View view){//拿到选中项的idint id = rg.getCheckedRadioButtonId() ;//判断id是谁switch (id) {case R.id.china:Toast.makeText(MainActivity.this, "你点击的是:中国" , 0).show() ;break;case R.id.america:Toast.makeText(MainActivity.this, "你点击的是:美国" , 0).show() ;break;case R.id.japan:Toast.makeText(MainActivity.this, "你点击的是:日本" , 0).show() ;break;}}


0 0
原创粉丝点击