RadioGroup的使用 day2

1、布局res/layout界面 有一个 小布局RadioGroup
//小布局里有三个RadioButton按钮
//一个Button按钮

代码

<LinearLayout 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"
    android:orientation="vertical" >

   <!-- 默认垂直排放 -->
    <RadioGroup
        android:id="@+id/radiogroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
       
         <RadioButton
            android:id="@+id/stone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="石头"
            android:textSize="50sp"
            />
         <RadioButton
            android:id="@+id/shear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="剪刀"
            android:textSize="50sp"/>
         <RadioButton
            android:id="@+id/cloth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="布"
            android:textSize="50sp"/>
 
   </RadioGroup>
  
<!-- 在Button 里面定义监听的第二种方法 onClick -->
  <Button
         android:id="@+id/submit"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="提交"
         android:textSize="50sp"
         android:onClick="onclick"
         />

</LinearLayout>
--------------------------------
2、在MainActivity里 添加代码

代码

public class MainActivity extends Activity {
private RadioGroup radiogroup;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  radiogroup = (RadioGroup) this.findViewById(R.id.radiogroup);
  //设置 组的监听 事件
//这里用的是seOnCheckedChangeListener()监听
  radiogroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
   
   @Override
//onCkeckedChanged方法里的 第二个参数表示 选中的RadioButton
   public void onCheckedChanged(RadioGroup group, int checkid) {
    // TODO Auto-generated method stub
    RadioButton check_radio = (RadioButton) findViewById(checkid);
    Toast.makeText(MainActivity.this, "出:" + check_radio.getText(), Toast.LENGTH_SHORT).show();
   }
  });
  
 }
//在布局界面 Button里面 定义的 监听
 public void onclick(View view){
//用RadioGroup 的对象调用getCheckedRadioButtonId 方法 来获取 当前 选中的 RadioButton
  int id = radiogroup.getCheckedRadioButtonId();
  RadioButton bt_id = (RadioButton)findViewById(id);
  Toast.makeText(MainActivity.this, "出:" + bt_id.getText(), Toast.LENGTH_SHORT).show();
 }
}

你可能感兴趣的:(RadioGroup的使用 day2)