facebook twitter hatena line email

Android/PreferenceFragmentCompat

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

Fragmentについて

Fragmentについて理解してない場合はこちら

android/Fragment [ショートカット]

PreferenceFragmentCompatを追加

build.gradleに以下を追加

dependencies {
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:preference-v7:28.0.0'
}

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.kaji.fragmentmyapplication.ui.main.PrefsFragment;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, PrefsFragment.newInstance())
                    .commitNow();
        }
    }
}

ui/main/PrefsFragment.java


import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.support.v7.preference.Preference;
import android.support.v7.preference.EditTextPreference;
import android.support.v7.preference.PreferenceScreen;

import com.kaji.fragmentmyapplication.R;

public class PrefsFragment extends PreferenceFragmentCompat {
    private EditTextPreference editTextPreference;
    public static PrefsFragment newInstance() {
        return new PrefsFragment();
    }
    @Override
    public void onCreatePreferences(Bundle bundle, String s) {
        setPreferencesFromResource(R.xml.preferences, s);

        editTextPreference = (EditTextPreference)findPreference("editTextId");
        if (editTextPreference.getText() == null || editTextPreference.getText().length() < 1) {
            editTextPreference.setSummary(getResources().getString(R.string.edit_text_hint));
        } else {
            editTextPreference.setSummary(editTextPreference.getText());
        }
        editTextPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                EditTextPreference editPref = (EditTextPreference)preference;
                if (editPref.getText() != null) {
                    editPref.setText(editPref.getText());
                }
                return true;
            }
        });
        editTextPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference,
                                              Object newValue) {
                EditTextPreference editPref = (EditTextPreference)preference;
                editPref.setSummary(newValue.toString());
                return true;
            }
        });
        // imageのPreferenceScreenをクリックしたとき
        PreferenceScreen imagePreference = (PreferenceScreen)getPreferenceScreen().findPreference("image");
        imagePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                //Intent intent = new Intent(getContext(), HogehogeActivity.class);
                //startActivity(intent);
                return true;
            }
        });
    }
}

res/layout/main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" />

res/layout/preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="red"
        android:summary="This is red."
        android:title="red" />
    <EditTextPreference
        android:key="editTextId"
        android:title="editText"
        android:summary="@string/edit_text_hint"
        android:hint="@string/edit_text_hint"
        />
    <PreferenceScreen android:key="image"
            android:title="image"
            />
</PreferenceScreen>

res/values/string.xml

<resources>
    <string name="app_name">FragmentMyApplication</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="edit_text_hint">hint</string>
</resources>

inconvertible types; cannnot cast Preferenceエラーが出る場合

古いPreferenceがあれば削除する

import android.preference.Preference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;

新しいPreferenceを追加

import android.support.v7.preference.Preference;
import android.support.v7.preference.EditTextPreference;
import android.support.v7.preference.ListPreference;
Preference screen = (Preference) getPreferenceManager().findPreference("key1");

or

Preference editTextPreference = (Preference) findPreference("key1");


com.android.support.support:customtabs:26.1.0 same versionエラーが出るとき

以下をapp/build.gradleへ追加

dependencies {
     implementation "com.android.support:customtabs:28.0.0"
     implementation 'com.android.support:support-media-compat:28.0.0'
     implementation 'com.android.support:support-v4:28.0.0'
}

java.lang.IllegalStateException: Must specify preferenceTheme in themeエラーが出たとき

res/values/styles.xml

   <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
       <item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
   </style>

@style/PreferenceThemeOverlayを追加

参考

【Android】続・PreferenceFragmentCompatを使った設定画面(kotrin?) http://phicdy.hatenablog.com/entry/setting_ui_by_preference_fragment_compat

PreferenceActivity/PreferenceFragmentを使った設定画面 http://phicdy.hatenablog.com/entry/2015/09/08/%E3%80%90Android%E3%80%91PreferenceActivity/PreferenceFragment%E3%82%92%E4%BD%BF%E3%81%A3%E3%81%9F%E8%A8%AD%E5%AE%9A%E7%94%BB%E9%9D%A2