버튼은 텍스트뷰를 상속하였다. 따라서 확장성이 뛰어난 버튼을 구성할 수 있다. 버튼은 onClickListener라는 콜백함수를 통해 이벤트가 발생했을 때(버튼이 눌렸을 때) 특정 기능을 처리하는 코드를 구성할 수 있다.
<?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">
<Button
android:id="@+id/dog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="개"
android:textSize="24dp"/>
<Button
android:id="@+id/cat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="고양이"
android:textSize="24dp"/>
</LinearLayout>
버튼을 두 개 추가하였다. 하나는 눌렀을 때 개가 짖는 행동을, 나머지 하나는 고양이가 우는 행동을 표현하기 위한 것이다. 이제 이벤트 처리를 위해 자바 코드를 작성해야 한다.
package io.swnomad.samplewidget;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* XML 레이아웃에 정의 된 버튼 객체 참조 */
Button dogButton = findViewById(R.id.dog);
Button catButton = findViewById(R.id.cat);
/* dogButton에 클릭이벤트 발생 시 "멍멍! 멍멍!" 문자열 토스트 메시지 출력 */
dogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "멍멍! 멍멍!", Toast.LENGTH_LONG).show();
}
});
/* catButton에 클릭이벤트 발생 시 "야옹~ 야옹~" 문자열 토스트 메시지 출력 */
catButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "야옹~ 야옹~", Toast.LENGTH_LONG).show();
}
});
}
}
XML 코드에서 버튼의 속성 중 onClick의 값으로 실행시킬 메소드의 이름을 설정하는 방법도 있지만, 지금처럼 버튼의 setOnClickListener 메소드를 통해 리스너 객체를 전달해줄 수도 있다. 이 때 리스너 객체는 익명 클래스로 만들어서 전달해주었다. 앱을 실행시켜서 버튼을 눌러보면 다음과 같은 결과가 나온다.
버튼을 확장한 기능인 체크박스(CheckBox)와 라디오버튼(RadioButton)에 대해서도 알아보자. 이 두 버튼의 경우 클릭 이벤트 이외에도 선택/해제 상태를 저장할 수 있다. 이는 CompoundButton이라는 클래스를 상속하기 때문이다.
컴파운드버튼(CompoundButton) 클래스의 주요 메소드로는 다음의 것들이 있다.
public boolean isChecked() // 선택/해제 상태를 return
public void setChecked(boolean checked) // true 혹은 false 값을 전달받아 선택/해제 상태값 지정
public void toggle() // 선택/해제 상태를 변경
void onCheckedChanged(CompoundButton buttonView, boolean isChecked) //상태가 바뀔경우 항상 호출되는 메소드
라디오 버튼은 하나를 선택하면 나머지 것들이 해제되어야 하므로 라디오 그룹(RadioGroup)을 사용해서 하나로 묶어준다. 이를 응용해서 간단한 앱을 하나 만들어보자.
<?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">
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="20dp"
android:layout_gravity="center_horizontal">
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="개"
android:textSize="20dp"/>
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="고양이"
android:textSize="20dp"/>
<RadioButton
android:id="@+id/radio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="돼지"
android:textSize="20dp"/>
</RadioGroup>
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#ffff00ff"
android:layout_marginBottom="20dp"
android:background="#ffaaffff"
android:gravity="center_horizontal"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal">
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="체크박스"
android:textSize="20dp"
android:layout_marginLeft="20dp"/>
</LinearLayout>
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#ffff00ff"
android:layout_marginBottom="20dp"
android:background="#ffaaffff"
android:gravity="center_horizontal"/>
</LinearLayout>
개, 고양이, 돼지 중 하나를 선택할 수 있는 라디오 버튼들을 라디오 그룹으로 묶어주었다. 또한 체크박스도 하나 만들어보았다. 각각의 버튼들 아래에는 텍스트뷰를 하나씩 만들어 어떠한 문자열을 표시하려 한다. 이제 기능을 구현하기 위한 자바코드를 만들어보자.
package io.swnomad.samplewidget;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
RadioButton radio1;
RadioButton radio2;
RadioButton radio3;
TextView textView1;
TextView textView2;
CheckBox checkBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* XML 레이아웃에 정의 된 라디오버튼, 텍스트뷰, 체크박스 객체 참조 */
radio1 = findViewById(R.id.radio1);
radio2 = findViewById(R.id.radio2);
radio3 = findViewById(R.id.radio3);
textView1 = findViewById(R.id.textView1);
textView2 = findViewById(R.id.textView2);
checkBox = findViewById(R.id.checkBox);
/* radio1 상태 변경 이벤트 발생 처리부 코드 */
radio1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
textView1.setText("개 입니다."); //textView1의 문자열 "개 입니다."로 설정
}
}
});
/* radio2 상태 변경 이벤트 발생 처리부 코드 */
radio2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
textView1.setText("고양이 입니다."); //textView1의 문자열 "고양이 입니다."로 설정
}
}
});
/* radio3 상태 변경 이벤트 발생 처리부 코드 */
radio3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
textView1.setText("돼지 입니다."); //textView1의 문자열 "돼지 입니다."로 설정
}
}
});
/* checkBox 상태 변경 이벤트 발생 처리부 코드 */
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
textView2.setText("체크되었습니다."); //textView2의 문자열 "체크되었습니다."로 설정
}else{
textView2.setText("체크가 해제되었습니다."); //textView2의 문자열 "체크가 해제되었습니다."로 설정
}
}
});
}
}
각각의 버튼마다 OnCheckedChangeLister를 달아주었다. 선택/해제 상태가 변경되면 OnCheckedChanged 메소드가 호출된다. 각각의 OnCheckedChanged 메소드로는 isChecked 변수가 전달되는데, 선택된 것이면 true가, 반대면은 false가 들어온다. 따라서 체크 되었을 때와 아닌 경우마다 textView에 표시되는 문자열을 다르게 설정하는 코드를 넣어준다. 그리고 앱을 실행하면 아래와 같은 화면이 나온다.
'안드로이드' 카테고리의 다른 글
(안드로이드) 14 - 인플레이션(Inflation) (0) | 2020.05.18 |
---|---|
(안드로이드) 13 - 기본 위젯(3) - 입력상자(EditText) (0) | 2020.05.18 |
(안드로이드) 11 - 기본 위젯(1) - 텍스트뷰(TextView) (0) | 2020.05.18 |
(안드로이드) 10 - 프레임 레이아웃(FrameLayout) (0) | 2020.05.18 |
(안드로이드) 9 - 스크롤 뷰(ScrollView) (0) | 2020.05.18 |