Question

J'ai tenté d'utiliser un android.preference.DialogPreference gonflé de XML, mais la documentation semble manquer quelques morceaux essentiels, et je ne peux pas trouver un exemple de travail nulle part. Mon XML ressemble maintenant à ceci (j'ai essayé beaucoup de permutations, mais cela semble un minimum raisonnable):

<DialogPreference
android:key="funThing" android:title="Fun Thing"
android:dialogLayout="@layout/fun_layout"
android:positiveButtonText="OK"
android:negativeButtonText="Cancel"
/>

Ma supposition à ce point est qu'il est nécessaire de la sous-classe DialogPreference et de ne pas utiliser directement. D'une part, je ne peux pas trouver un moyen d'associer la valeur de préférence réelle avec un élément dans la boîte de dialogue lui-même, qui, après réflexion est une sorte de cadeau. Et aussi, regardant la source DialogPreference.java semble le confirmer. Et je viens de remarquer aussi que la documentation officielle y fait référence comme " classe de base ». Mais à tout le moins, ce serait bien d'établir une source définitive, assez sur le net qui aiderait les gens à venir N comprendre cela plus vite que moi.

Pour mémoire, les regards du fichier journal comme celui-ci:

I/ActivityManager(   61): Starting: Intent { cmp=org.jeremy.android/.PreferencesActivity } from pid 2755
W/Resources( 2755): Converting to string: TypedValue{t=0x10/d=0x4b0 a=-1}
W/Resources( 2755): Converting to string: TypedValue{t=0x10/d=0x20 a=-1}
D/AndroidRuntime( 2755): Shutting down VM
W/dalvikvm( 2755): threadid=1: thread exiting with uncaught exception (group=0x40015560)
E/AndroidRuntime( 2755): FATAL EXCEPTION: main
E/AndroidRuntime( 2755): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.jeremy.android/org.jeremy.android.PreferencesActivity}: android.view.InflateException: Binary XML file line #28: Error inflating class java.lang.reflect.Constructor
E/AndroidRuntime( 2755):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
E/AndroidRuntime( 2755):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
E/AndroidRuntime( 2755):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
E/AndroidRuntime( 2755):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
E/AndroidRuntime( 2755):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 2755):    at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime( 2755):    at android.app.ActivityThread.main(ActivityThread.java:3683)
E/AndroidRuntime( 2755):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 2755):    at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime( 2755):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime( 2755):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime( 2755):    at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 2755): Caused by: android.view.InflateException: Binary XML file line #28: Error inflating class java.lang.reflect.Constructor
E/AndroidRuntime( 2755):    at android.preference.GenericInflater.createItem(GenericInflater.java:397)
E/AndroidRuntime( 2755):    at android.preference.GenericInflater.onCreateItem(GenericInflater.java:417)
E/AndroidRuntime( 2755):    at android.preference.GenericInflater.createItemFromTag(GenericInflater.java:428)
E/AndroidRuntime( 2755):    at android.preference.GenericInflater.rInflate(GenericInflater.java:481)
E/AndroidRuntime( 2755):    at android.preference.GenericInflater.rInflate(GenericInflater.java:493)
E/AndroidRuntime( 2755):    at android.preference.GenericInflater.inflate(GenericInflater.java:326)
E/AndroidRuntime( 2755):    at android.preference.GenericInflater.inflate(GenericInflater.java:263)
E/AndroidRuntime( 2755):    at android.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:251)
E/AndroidRuntime( 2755):    at android.preference.PreferenceActivity.addPreferencesFromResource(PreferenceActivity.java:262)
E/AndroidRuntime( 2755):    at org.jeremy.android.PreferencesActivity.onCreate(PreferencesActivity.java:40)
E/AndroidRuntime( 2755):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
E/AndroidRuntime( 2755):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
E/AndroidRuntime( 2755):    ... 11 more
E/AndroidRuntime( 2755): Caused by: java.lang.InstantiationException: android.preference.DialogPreference
E/AndroidRuntime( 2755):    at java.lang.reflect.Constructor.constructNative(Native Method)
E/AndroidRuntime( 2755):    at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
E/AndroidRuntime( 2755):    at android.preference.GenericInflater.createItem(GenericInflater.java:383)
E/AndroidRuntime( 2755):    ... 22 more
W/ActivityManager(   61):   Force finishing activity org.jeremy.android/.PreferencesActivity
W/ActivityManager(   61):   Force finishing activity org.jeremy.android/.SplashActivity
Était-ce utile?

La solution

Celui-ci est bizarre, vous avez besoin de sous-classe DialogPreference. La sous-classe n'a pas besoin de faire quoi que ce soit. Donc,

public class MyDialogPreference extends DialogPreference {

    public MyDialogPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

} 

peut être instancié. Alors qu'un avion ancien DialogPreference ne peut pas. Très bizarre, ils devraient être exactement la même chose.

Autres conseils

Voici un exemple de la façon d'utiliser la préférence de dialogue (sous-classement comme vous l'avez mentionné).

package dk.myapp.views;

import android.content.Context;
import android.preference.DialogPreference;
import android.util.AttributeSet;

/**
 * The OptionDialogPreference will display a dialog, and will persist the
 * <code>true</code> when pressing the positive button and <code>false</code>
 * otherwise. It will persist to the android:key specified in xml-preference.
 */
public class OptionDialogPreference extends DialogPreference {

    public OptionDialogPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);
        persistBoolean(positiveResult);
    }

}

Le preferences.xml doit contenir

<dk.myapp.views.OptionDialogPreference
            android:key="@string/prefKeyResetQuests"
            android:dialogIcon="@android:drawable/ic_dialog_alert"
            android:title="Reset Quests"
            android:summary="Reset all quest-progress."
            android:dialogMessage="Are you sure you wish to reset your quest progress? This action cannot be undone!"
            android:positiveButtonText="Clear Quests"
            android:negativeButtonText="Cancel"/>

J'ai res / valeur contenant (bien que le nom de clé peut également être déclarée explicitement ci-dessus).

<string name="prefKeyResetQuests">resetQuests</string>  

Mon PreferenceActivity fait la remise à zéro réelle de OnPause. Notez que onStop peut être trop tard puisque le onStop ne sera pas toujours appelé immédiatement après avoir appuyé sur retour:

@Override
public void onPause() {
    SharedPreferences prefs = android.preference.PreferenceManager.
        getDefaultSharedPreferences(getBaseContext());
    if(prefs.getBoolean(
        getResources().getString(R.string.prefKeyResetQuests), false)) {
        // apply reset, and then set the pref-value back to false
    }
}

Ou, puisque nous sommes qui revient toujours dans le PreferenceActivity:

@Override
protected void onPause() {
    Preference prefResetQuests =
        findPreference(getResources().getString(R.string.prefKeyResetQuests));
    if(prefResetQuests.getSharedPreferences().
        getBoolean(prefResetQuests.getKey(), false)){
        // apply reset, and then set the pref-value back to false 
    }
}

Première:

Créez votre propre classe qui étend DialogPreference comme ci-dessous:

package com.test.view;

import android.preference.DialogPreference;

public class DialogExPreference extends DialogPreference 
{
    public DialogExPreference(Context oContext, AttributeSet attrs)
    {
        super(oContext, attrs);     
    }
}

Second:

Modifier le fichier xml comme ci-dessous:

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

    <com.test.view.DialogExPreference
        android:title="@string/title"
        android:dialogMessage="@string/lite"              
                android:negativeButtonText="test"/> 

</PreferenceScreen>

Ensuite, il est OK.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top