Getting Started with Android. Radio Buttons RadioButton and RadioGroup

RadioButton RadioButton
RadioGroup

Each RadioGroup is a group, and in a group, there is only one radio button RadioButton


1. XML Liberal Arts
<RadioGroup/> <RadioButton/>
<RadioButton/> is a child tag of <RadioGroup/>

<RadioGroup
	    android:id="@+id/radioGroup"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    >
	    <RadioButton
	        android:id="@+id/nv"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:text="女"
	        />
	    <RadioButton
	        android:text="男"
	        android:id="@+id/nan"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        />
	</RadioGroup>

2. Code
FindViewById finds the control


3. Listener
OnClickListener,OnCheckedChangeListener





private RadioGroup radioGroup;
	private RadioButton buttonNv;
	private RadioButton buttonNan;

	// Don't import wrong, import the radioButton package and implement the listening interface
	class RadioGroupListener implements OnCheckedChangeListener {
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			if (buttonNan.getId() == checkedId) {
				System.out.println("女");
			} else if (buttonNv.getId() == checkedId) {
				System.out.println("男");
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView(R.layout.activity_main);

		radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
		buttonNan = (RadioButton) findViewById(R.id.nan);//2.FindViewById finds the control
		buttonNv = (RadioButton) findViewById(R.id.nv);

		RadioGroupListener listener = new RadioGroupListener();
		radioGroup.setOnCheckedChangeListener(listener);3. Listener

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327059835&siteId=291194637