공부/안드로이드(Android)

이벤트 - 라디오 그룹, 라디오 버튼

도도-도윤 2017. 11. 7. 21:38

이벤트 - 라디오 그룹, 라디오 버튼


라디오 그룹과 라디오 버튼에 대해서 소개합니다.

이벤트 처리에 대해서 설명합니다.



1. RadioGroup과 RadioButton 만들기





크게 라디오 버튼은 라디오 그룹을 먼저 만들고 난 후에 만드는 것으로 생각하면 될 것입니다.



2. 실습




 라디오 그룹 및 라디오 버튼 만들기 실습




3. 소스코드


 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.lab.program.MainActivity">


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

<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="Red" />

<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="Blue" />
</RadioGroup>
</LinearLayout>

 Activity.xml

 

public class MainActivity extends AppCompatActivity {

private View.OnClickListener radioListener = new View.OnClickListener() {
@Override
public void onClick(View view) {

RadioButton rb = (RadioButton)view;

if ( rb.isChecked() ){
Toast.makeText(getApplicationContext(), "Checked", Toast.LENGTH_SHORT).show();
}else
Toast.makeText(getApplicationContext(), "UnChecked", Toast.LENGTH_SHORT).show();

}
};

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

final RadioButton red = (RadioButton)findViewById(R.id.radio1);
final RadioButton blue = (RadioButton)findViewById(R.id.radio2);

red.setOnClickListener(radioListener);
blue.setOnClickListener(radioListener);

}

}

 main_activity.java