Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách thêm Button vào PreferenceScreen trên Android

Giới thiệu

Ví dụ này minh họa cách thêm một mục tùy chọn (Preference) hoạt động như Button trong màn hình Settings (PreferenceScreen) bằng PreferenceFragmentCompat.

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio → File → New Project → Chọn template "Settings Activity" (hoặc Empty Activity rồi thêm sau).

Bước 2: Layout chính (res/layout/activity_main.xml)

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

Bước 3: Code MainActivity (src/MainActivity.java)

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(preference -> {
                    Toast.makeText(getActivity(), "Preference button được nhấn", Toast.LENGTH_SHORT).show();
                    return true;
                });
            }
        }
    }
}

Bước 4: XML Preferences (res/xml/root_preferences.xml)

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

        <!-- Button Preference -->
        <Preference
            app:key="toastMsg"
            app:title="Hiển thị 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>

Bước 5: String & Array Resources (res/values/strings.xml, arrays.xml)

<!-- strings.xml -->
<resources>
    <string name="messages_header">Tin nhắn</string>
    <string name="signature_title">Chữ ký</string>
    <string name="reply_title">Trả lời tự động</string>
    <string name="sync_header">Đồng bộ</string>
    <string name="sync_title">Bật đồng bộ</string>
    <string name="attachment_title">Tải đính kèm</string>
    <string name="attachment_summary_on">Tự động tải khi có Wi-Fi</string>
    <string name="attachment_summary_off">Chỉ tải khi nhấn</string>
</resources>

<!-- arrays.xml -->
<resources>
    <string-array name="reply_entries">
        <item>Trả lời ngay</item>
        <item>Trả lời sau 1 giờ</item>
        <item>Không trả lời</item>
    </string-array>
    <string-array name="reply_values">
        <item>immediate</item>
        <item>delayed</item>
        <item>never</item>
    </string-array>
</resources>

Bước 6: Manifest (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"
            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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Mở màn hình Settings, nhấn mục "Hiển thị Toast" để xem kết quả.

Cách thêm Button vào PreferenceScreen trên Android Cách thêm Button vào PreferenceScreen trên Android

Giải thích

  • Preference với key toastMsg hiển thị như một mục nhấn được (như Button).
  • setOnPreferenceClickListener xử lý sự kiện nhấn.
  • Có thể dùng cho: "Xóa cache", "Đăng xuất", "Mở trang web", "Kiểm tra cập nhật"... không cần tạo Activity riêng.