이 튜토리얼에서는 안드로이드(Android) 앱에서 버튼을 클릭했을 때 버튼의 색상을 변경하는 방법을 단계별로 살펴봅니다. 레이아웃 XML부터 자바 코드, 매니페스트 설정까지 전체 과정을 예제와 함께 정리했으니 초보자도 쉽게 따라 할 수 있습니다.
1단계: 새 프로젝트 생성하기
Android Studio를 실행한 뒤 File → New Project 메뉴로 이동하여 새 프로젝트를 생성합니다. 프로젝트 생성에 필요한 기본 정보를 모두 입력한 후 진행하세요.
2단계: 레이아웃 파일 작성 (activity_main.xml)
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에 클릭 가능한 버튼 하나를 배치하는 간단한 구성입니다.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click here to change color!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
</android.support.constraint.ConstraintLayout>
3단계: 메인 액티비티 코드 작성 (MainActivity.java)
src/MainActivity.java에 다음 코드를 추가합니다. 핵심은 setOnClickListener()로 클릭 이벤트를 감지한 뒤, setBackgroundColor() 메서드로 버튼의 배경색을 변경하는 부분입니다.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
button.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
});
}
}
참고: 최신 안드로이드 API에서는
getResources().getColor()가 deprecated되었습니다. 호환성을 위해ContextCompat.getColor(context, R.color.colorPrimary)사용을 권장합니다.
4단계: AndroidManifest.xml 설정 확인
androidManifest.xml 파일이 아래와 같이 올바르게 구성되어 있는지 확인합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 상단 툴바의 Run 아이콘을 클릭하세요. 실행 옵션 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

버튼을 클릭하면 colorPrimary에 정의된 색상으로 버튼의 배경색이 즉시 변경되는 것을 확인할 수 있습니다.
