Please Enable JavaScript!
Gon[ Enable JavaScript ]

안드로이드(Android) RadioGroup 과 RadioButton 이용한 예제

안드로이드 개발
반응형

안드로이드(Android) RadioGroup RadioButton 이용한 예제

 

개발환경 : window 7 64bit, Eclipse Mars, Android 4.2.2

 

옵션버튼(Radio button) 은 체크 박스와 달리 여러 개를

동시에 체크할수 없습니다. 하나가 체크되면

다른 것은 체크에서 해제 되어야 합니다. 이렇게

동시에 제어를 편리 하게 하기 위해 RadioGroup 클래스를

제공하며 RadioButton 을 묶어서 관리 합니다.

 

 

메인 레이아웃을 꾸미는 xml 에는 RadioGroup 위젯과

그 속에 포함되어 있는 RadioButton 위젯으로 구성

되어 있습니다. RadioGroup 위젯이 3개의 RadioButton

통제하는 것이죠.

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <RadioButton
            android:id="@+id/option1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Option 1" />

        <RadioButton
            android:id="@+id/option2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Option 2" />

        <RadioButton
            android:id="@+id/option3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Option 3" />
    </RadioGroup>

</LinearLayout>

 

메인 activity 에서는 각 옵션 객체에 클릭이벤트를

등록합니다. 그리고 첫번째 옵션버튼을 체크된 것으로 셋팅합니다.

 

option1 = (RadioButton) findViewById(R.id.option1);
option2 = (RadioButton) findViewById(R.id.option2);
option3 = (RadioButton) findViewById(R.id.option3);
option1.setOnClickListener(optionOnClickListener);
option2.setOnClickListener(optionOnClickListener);
option3.setOnClickListener(optionOnClickListener);
option1.setChecked(true);

 

등록한 이벤트에서 click 을 일어났을 때 Toast 객체를

사용하 각각의 옵션버튼이 체크 되었는지 아닌지 여부를

메시지로 알려줍니다.

 

RadioButton.OnClickListener optionOnClickListener 
		= new RadioButton.OnClickListener() {
	
	public void onClick(View v) {
		Toast.makeText(
				SampleActivity22.this,
				"Option 1 : " + option1.isChecked() + "\n"
						+ "Option 2 : " + option2.isChecked() + "\n"
						+ "Option 3 : " + option3.isChecked(),
				Toast.LENGTH_LONG).show();

	}
};

 

이번 예제는 간단해서 전체 소스가 없어도 되겠네요.

실행한 화면입니다.

 

안드로이드(Android) RadioGroup 과 RadioButton 이용한 예제

반응형
Posted by 녹두장군1
,