安卓基本控件之RadioButton

佈局文件

<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;
        }
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章