安卓基本控件之RadioButton

来源:互联网 发布:不收费小说软件 编辑:程序博客网 时间:2024/06/05 20:13

布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     >
     <!--RadioGroup  是LinearLayout的子类  
     android:checked="true"  是默认选中
      -->
     
     

    <RadioGroup
        android:id="@+id/rg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        <RadioButton
            android:id="@+id/rb_female"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="美女"
            android:onClick="onRadioBtn"
            android:checked="true"
            />
        <RadioButton
             android:id="@+id/rb_male"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="帅哥"
            android:onClick="onRadioBtn"
            />
        
    </RadioGroup>

</RelativeLayout>

Java代码

package com.qianfeng.day03_radiobutton;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends Activity {

    private RadioButton rb_female, rb_male;
    private RadioGroup rg ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //通过findViewById 找到相应的控件
        rg = (RadioGroup) findViewById(R.id.rg);
        
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            // 参数1:你点击的RadioButton的组 参数2:是你选中的控件的id
            
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub
                RadioButton rb = (RadioButton) findViewById(checkedId);
                //参数1:上下文对象  参数2:显示的文本信息 参数3:显示的时间
                Toast.makeText(MainActivity.this, rb.getText().toString(), 0).show();
            }
        });
    }

    //radioButton的点击事件
    public void onRadioBtn(View v) {
        RadioButton rb = (RadioButton) v;// 转型  得到点击的按钮
        boolean isChecked = rb.isChecked();//得到按钮的状态
        switch (v.getId()) {
//        case R.id.rb_female:
//            Toast.makeText(MainActivity.this, "美女", Toast.LENGTH_SHORT).show();
//            break;
//        case R.id.rb_male:
//            Toast.makeText(MainActivity.this, "帅哥", Toast.LENGTH_SHORT).show();
//            break;

        default:
            break;
        }
    }
}



0 0
原创粉丝点击