//示例RadioButton,一般都和RadioGroup组合一起用
public class MainActivity extends Activity {
private RadioGroup group;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
group=(RadioGroup) this.findViewById(R.id.group);
//设置组的监听事件: OnCheckedChangeListener
group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
//在组中获取按钮点击后的事件内容
@Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
RadioButton radiobutton1=(RadioButton) findViewById(arg1);
Toast.makeText(MainActivity.this, "勾选了:" +radiobutton1.getText(), Toast.LENGTH_SHORT).show();
}
});
}
//注意:这个是在外面,组外获取组内按钮的事件内容,一般比较常用的是组外获取
public void guess(View view){
int id=group.getCheckedRadioButtonId();
RadioButton radiobutton2=(RadioButton) findViewById(id);
Toast.makeText(MainActivity.this, "勾选了:" +radiobutton2.getText(), Toast.LENGTH_SHORT).show();
}
}
//布局
<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"
tools:context="${relativePackage}.${activityClass}" >
<RadioGroup
android:id="@+id/group"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/stone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="石头"
/>
<RadioButton
android:id="@+id/sheet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="布"
/>
<RadioButton
android:id="@+id/scissor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="剪刀"
/>
</RadioGroup>
<Button
android:id="@+id/sumbit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="出拳"
android:onClick="guess"
/>
</LinearLayout>
转载于:https://my.oschina.net/u/2541146/blog/603628