<--! 안드로이드 - 라디오버튼 만들기 -->

안드로이드 - 라디오버튼 만들기

필그램

·

2017. 7. 26. 07:04

라디오 버튼을 만드는 소스 입니다.


앱 테스트는 아래 그림처럼 할 예정입니다.



먼저 xml을 만듭니다.

Activity_main.xml  이 되겠고.


버튼중 1번이 선택 되게 하는 것은 첫번째 버튼 코드의  android:checked="true" 입니다.

<?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" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="안녕하세요"
android:textSize="24sp"/>

<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<RadioButton
android:id="@+id/radio_two_way"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Two way" />

<RadioButton
android:id="@+id/radio_one_way"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="one way" />
</RadioGroup>

<Button
android:id="@+id/button_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ok" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>


위 코드의 맨아래 텍스트 뷰는 각 버튼 선택시 선택 내용을 보여주는 부분입니다. 아래 그림처럼 첫번째 버튼 선택후 OK  버튼을 누르면  버튼 아래중에 'two way'라고 뜨게 됩니다.



MainActivity.java

mport android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private RadioGroup choiceWay;
int selectedValueId;
RadioButton oneWay;
TextView textMessage;

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

//버튼
Button button =(Button) findViewById(R.id.button_ok);
//라디오 그룹
choiceWay = (RadioGroup) findViewById(R.id.radioGroup1);
//라디오버튼
oneWay = (RadioButton) findViewById(R.id.radio_one_way);
//맨아래 텍스트 라인
textMessage = (TextView) findViewById(R.id.textView1);


//button click listener
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//getting the id of selected radio button
selectedValueId = choiceWay.getCheckedRadioButtonId();
//checking the id of the selected radio
if(selectedValueId == oneWay.getId())
{
//선택한것이 원웨이 첫번째 것이면 아래 출력
textMessage.append("one way ");
//append를 함으로써, 두번 세번째 버튼 클릭시 계속 연결되어 써집니다

}
else
{
//선택한것이 원웨이 첫번째 것이 아니면 아래 출력
textMessage.append("two way ");

}
}
});
}
}


반응형