MainActivity.java
package com.jk.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class MainActivity extends Activity {
private RadioButton eatButton;
private RadioButton sleepButton;
private RadioButton dotaButton;
private RadioGroup groupButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eatButton = (RadioButton) findViewById(R.id.eatButtonid);
sleepButton = (RadioButton) findViewById(R.id.sleepButtonid);
dotaButton = (RadioButton) findViewById(R.id.dotaButtonid);
RadioGroupListener listener1 = new RadioGroupListener();
groupButton.setOnCheckedChangeListener(listener1);
RadioButtonListener listener2 = new RadioButtonListener();
eatButton.setOnCheckedChangeListener(listener2);
sleepButton.setOnCheckedChangeListener(listener2);
dotaButton.setOnCheckedChangeListener(listener2);
}
class RadioButtonListener implements OnCheckedChangeListener{
public void onCheckedChanged(CompoundButton v, boolean isChecked) {
System.out.println(v.getId()+"isChecked--->" + isChecked);
}
}
class RadioGroupListener implements android.widget.RadioGroup.OnCheckedChangeListener{
public void onCheckedChanged(RadioGroup v, int checkedId) {
if(checkedId == eatButton.getId())
System.out.println("选中了eatButton");
else if(checkedId == sleepButton.getId())
System.out.println("选中了sleepButton");
else if(checkedId == dotaButton.getId())
System.out.println("选中了dotaButton");
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<RadioGroup
android:id="@+id/radioGroupId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/eatButtonid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="吃饭"
/>
<RadioButton
android:id="@+id/sleepButtonid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="睡觉"
/>
<RadioButton
android:id="@+id/dotaButtonid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dota"
/>
</RadioGroup>
</LinearLayout>