RadioButton 사용하기
package org.kosta.radiobtn.test;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
RadioGroup ageRG = (RadioGroup)findViewById(R.id.age_rg);
//RadioGroup내에 선택된 RadioButton의 ID를 조회
int id = ageRG.getCheckedRadioButtonId();//선택된 것의 ID를 리턴해줌(R.java에 있는 0x1111과 같은 값을 리턴해줌)
RadioButton rd = (RadioButton) findViewById(id);//text로 ID를 리턴하도록 변환
String txt = (String)rd.getText();//rd값을 얻어옴
Toast.makeText(MainActivity.this, txt, Toast.LENGTH_SHORT).show();//화면에 짧은 시간 txt 값을 보여줌
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="나이를 선택하세요"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/age_rg">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="10대"
android:id="@+id/age1"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="20대"
android:id="@+id/age2"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="30대"
android:id="@+id/age3"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="40대"
android:id="@+id/age4"/>
</RadioGroup>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="선택 나이 조회"
android:id="@+id/btn"/>
</LinearLayout>
* 결과