LoginSignup
0
1

More than 3 years have passed since last update.

[Android]設定画面の設定項目をすべて一覧する

Last updated at Posted at 2019-08-18

環境

  • androidx.preference 1.0.0

コード

以下の例では、設定のキーをすべてログ出力している。
キモになるのは、一覧した PreferencePreferenceGroup が紛れ込んでいるところ。

PreferenceScreen prefScreen = getPreferenceScreen();
int prefCount = prefScreen.getPreferenceCount();

for (int i = 0; i < prefCount; i++) {
    Preference pref = prefScreen.getPreference(i);
    if (pref instanceof PreferenceGroup) {
        setupPrefsRecursive((PreferenceGroup)pref);
    } else if (!Strings.isNullOrEmpty(pref.getKey())) {
        Log.i(TAG, pref.getKey());
    }
}

private void setupPrefsRecursive(PreferenceGroup prefGroup) {
    int prefGroupCount = prefGroup.getPreferenceCount();
    for (int i = 0; i < prefGroupCount; i++) {
        Preference pref = prefGroup.getPreference(i);
        if (pref instanceof PreferenceGroup) {
            setupPrefsRecursive((PreferenceGroup)pref);
        } else if (!Strings.isNullOrEmpty(pref.getKey())) {
            Log.i(TAG, pref.getKey());
        }
    }
}

で以下のような設定があったとすると

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:mozc="http://schemas.android.com/apk/res-auto">
    <PreferenceCategory android:title="@string/pref_cat_1">
        <CheckBoxPreference
            android:defaultValue="false"
            android:key="pref_key_1"
            android:title="@string/pref_title1" />

        <PreferenceCategory android:title="@string/pref_cat_1_1">

            <Preference
                android:key="pref_key_2"
                android:persistent="false"
                android:title="@string/pref_title2">
            </Preference>
        </PreferenceCategory>
    </PreferenceCategory>

    <PreferenceCategory android:title="@string/pref_cat_2">
        <CheckBoxPreference
            android:defaultValue="true"
            android:key="pref_key_3"
            android:title="@string/pref_title3" />
    </PreferenceCategory>
</PreferenceScreen>

以下のような出力になる。

pref_key_1
pref_key_2
pref_key_3

参考

特に無かったから書いた。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1