1. 程式人生 > >Android中Radio單選按鈕操作

Android中Radio單選按鈕操作

public class MainActivity extends Activity {
	
	private RadioGroup group_temo;
	
	private RadioButton checkRadioButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		group_temo = (RadioGroup) findViewById(R.id.radioGroup1);
		
		//改變預設選項
		group_temo.check(R.id.radio1);
		
		
		//獲取預設被被選中值
		
		checkRadioButton = (RadioButton) group_temo.findViewById(group_temo.getCheckedRadioButtonId());
		
		
		Toast.makeText(this, "預設的選項的值是:"+checkRadioButton.getText(), Toast.LENGTH_LONG).show();
		
		//註冊事件
		group_temo.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				
				//點選事件獲取的選擇物件
				checkRadioButton = (RadioButton) group_temo.findViewById(checkedId);
				
				Toast.makeText(getApplicationContext(), "獲取的ID是"+checkRadioButton.getText(), Toast.LENGTH_LONG).show();
			}
		});
	}

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

}