이 튜토리얼에서는 안드로이드 앱의 PreferenceScreen(환경설정 화면)에 버튼을 추가하고, 클릭 이벤트를 처리하는 방법을 단계별로 알아봅니다.
1단계: 새 프로젝트 생성
Android Studio를 실행한 후 File → New Project 메뉴로 이동하여 새 프로젝트를 생성합니다. 프로젝트 생성에 필요한 모든 세부 정보(프로젝트 이름, 패키지명, 최소 SDK 버전 등)를 입력합니다.
2단계: activity_main.xml 레이아웃 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 환경설정 프래그먼트가 표시될 FrameLayout 컨테이너를 정의합니다.
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/settings"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
3단계: MainActivity.java 구현
src/MainActivity.java 파일에 다음 코드를 작성합니다. 핵심은 PreferenceFragmentCompat을 상속받은 내부 클래스에서 findPreference() 메서드로 버튼을 찾아 클릭 리스너를 등록하는 부분입니다.
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
getSupportFragmentManager().beginTransaction().replace(R.id.settings, new SettingsFragment()).commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
Preference button = getPreferenceManager().findPreference("toastMsg");
if (button != null) {
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference arg0) {
Toast.makeText(getActivity(), "Preference button is clicked",
Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
}
}
4단계: root_preferences.xml에 버튼 정의
res/xml/root_preferences.xml 파일에 아래 코드를 추가합니다. 여기서 중요한 점은 일반적인 Button 위젯이 아니라 Preference 요소를 사용한다는 것입니다. app:key="toastMsg" 속성으로 지정한 키 값이 자바 코드에서 버튼을 찾는 기준이 됩니다.
<PreferenceScreen xmlns:app="https://schemas.android.com/apk/res-auto">
<PreferenceCategory app:title="@string/messages_header">
<EditTextPreference
app:key="signature"
app:title="@string/signature_title"
app:useSimpleSummaryProvider="true" />
<ListPreference
app:defaultValue="reply"
app:entries="@array/reply_entries"
app:entryValues="@array/reply_values"
app:key="reply"
app:title="@string/reply_title"
app:useSimpleSummaryProvider="true" />
<Preference
app:key="toastMsg"
app:title="Show me a Toast" />
</PreferenceCategory>
<PreferenceCategory app:title="@string/sync_header">
<SwitchPreferenceCompat
app:key="sync"
app:title="@string/sync_title" />
<SwitchPreferenceCompat
app:dependency="sync"
app:key="attachment"
app:summaryOff="@string/attachment_summary_off"
app:summaryOn="@string/attachment_summary_on"
app:title="@string/attachment_title" />
</PreferenceCategory>
</PreferenceScreen>
5단계: AndroidManifest.xml 설정 확인
androidManifest.xml 파일이 아래와 같이 작성되어 있는지 확인합니다. MainActivity가 런처(LAUNCHER) 액티비티로 등록되어 있어야 앱 실행 시 환경설정 화면이 바로 나타납니다.
<?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"
android:label="@string/title_activity_settings">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰이 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 상단 툴바의 Run(실행) 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면 기기 화면에 아래와 같은 결과가 표시됩니다.


핵심 포인트 정리
- PreferenceScreen에는 일반 Button 대신 Preference 요소를 사용해야 합니다.
- XML에서 지정한
app:key값을 통해 자바 코드에서 해당 항목을 찾을 수 있습니다. setOnPreferenceClickListener()를 사용하면 버튼처럼 클릭 이벤트를 처리할 수 있습니다.