1

CheckBoxPreference を含む .xml ファイルからコンテンツが読み込まれる PreferentFragment があります。

    <CheckBoxPreference
          android:title="@string/pref_secure_conn"
          android:key="enable_secure_connection"
          android:defaultValue="false"/>

ご存知のように、ユーザーがこの設定を操作すると、SharedPreferences オブジェクトが自動的に更新され、android:key に適切なブール値が含まれるようになります。

ただし、ブール値の代わりに文字列を使用したいと思います。後でそのキーで getString を呼び出すことができるように、CheckBoxPreference にブール値の代わりに文字列値を使用させる方法はありますか?

現在、「onSharedPreferenceChanged」を聞いて手動で変更しているだけですが、もっと良い方法があるかもしれません。(別の明白な修正は、この値が必要なときに getString の代わりに getBoolean を使用することですが、それができないと仮定しましょう)

4

3 に答える 3

0

私が考えることができる最も簡単な方法は、CheckBoxPreference を継承し、Preference を冗長に保存することです。

package com.example.preferencestest;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.CheckBoxPreference;
import android.util.AttributeSet;

public class StringCheckBoxPreference extends CheckBoxPreference {
    public StringCheckBoxPreference(Context context) { super(context); }
    public StringCheckBoxPreference(Context context, AttributeSet attrs) { super(context, attrs); }
    public StringCheckBoxPreference(Context context, AttributeSet attrs,
            int defStyle) { super(context, attrs, defStyle); }

    @Override
    public void setChecked(boolean checked) {
        super.setChecked(checked);
        SharedPreferences p = getSharedPreferences();
        SharedPreferences.Editor e = p.edit();
        e.putString(getKey()+"asString", String.valueOf(checked));
        e.apply();
    }
}

次のように、このクラスを PreferencesActivity xml に追加できます。

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <com.example.preferencestest.StringCheckBoxPreference
        android:defaultValue="true"
        android:key="myCheckBox"
        android:summary="@string/pref_description_social_recommendations"
        android:title="@string/pref_title_social_recommendations"
    />

    <CheckBoxPreference
        android:defaultValue="true"
        android:key="example_checkbox"
        android:summary="@string/pref_description_social_recommendations"
        android:title="@string/pref_title_social_recommendations" />
于 2014-10-16T09:34:13.800 に答える