简体   繁体   中英

show alert dialog when click item in listpreference-android

hello everyone i am new to android development.i want to open a alert dialog when user choose any theme in list preference in preference activity.i search lot in google but did not find any appropriate answer.here is my PrefenceActivity.

public class Setting extends PreferenceActivity { 

    /** Called when the activity is first created. */  
        @Override  
        public void onCreate(Bundle savedInstanceState) { 
            Setting.setAppTheme(this);
            super.onCreate(savedInstanceState);  
            addPreferencesFromResource(R.xml.prefs); 

        } 


    String ListPreference;  

        public static void setAppTheme(Activity a)  {  
            // Get the xml/preferences.xml preferences  
            SharedPreferences prefs = PreferenceManager  
                            .getDefaultSharedPreferences(a); 
         int ListPreference = Integer.parseInt(prefs.getString("listPref", "3"));
         if(ListPreference == 0) {
                a.setTheme(R.style.AppBaseThemeDark);
                return;
                } else if(ListPreference == 1){
                    a.setTheme(R.style.AppBaseThemeLight);
                    //Toast.makeText(getApplicationContext(),"TTS Engines not found.\n Install TTS Engins",Toast.LENGTH_LONG).show();
                } else if(ListPreference == 2){
                    a.setTheme(R.style.AppBaseTheme);
                }

   }

        public boolean onCreateOptionsMenu(Menu menu) {
            super.onCreateOptionsMenu(menu);
            getActionBar().setDisplayHomeAsUpEnabled(true);

            return true;
        }
     public boolean onOptionsItemSelected(MenuItem item) {
         switch (item.getItemId()) {
                case android.R.id.home:
                        // app icon in action bar clicked; go home
                    getFragmentManager().popBackStack();
                    finish();
                        return true;

            }
            return super.onOptionsItemSelected(item);


}
}

I faced the same problem a few days ago and I implemented a custom preference class extending ListPreference to do this. This is the class I implemented:

public class LogCleanPreference extends ListPreference {
    private int mClickedDialogEntryIndex;
    
    private Context mContext;

    public LogCleanPreference(Context ctxt) {
        this(ctxt, null);
    }

    public LogCleanPreference(Context ctxt, AttributeSet attrs) {
        super(ctxt, attrs);
        
        mContext = ctxt;

        setNegativeButtonText(ctxt.getString(R.string.alert_cancel));
    }

    @Override
    protected void onPrepareDialogBuilder(Builder builder) {
        if (getEntries() == null || getEntryValues() == null) {
            throw new IllegalStateException(
                    "ListPreference requires an entries array and an entryValues array.");
        }

        mClickedDialogEntryIndex = findIndexOfValue(getValue());
        builder.setSingleChoiceItems(getEntries(), mClickedDialogEntryIndex, 
                new DialogInterface.OnClickListener() {
            public void onClick(final DialogInterface dialog, final int which) {
                // In my case I only show the AlertDialog if the user didn't select option number 2
                if(which != 2){
                    // Show AlertDialog
                }
                else{
                    // Save preference and close dialog
                    mClickedDialogEntryIndex = which;
    
                    LogCleanPreference.this.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
                    dialog.dismiss();
                }
            }
        });

        builder.setPositiveButton(null, null);
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {

        CharSequence[] mEntryValues = getEntryValues();

        if (positiveResult && mClickedDialogEntryIndex >= 0 && mEntryValues != null) {
            String value = mEntryValues[mClickedDialogEntryIndex].toString();
            if (callChangeListener(value)) {
                setValue(value);
            }
        }
    }
}

This is how I use the preference in my prefs.xml:

<com.timeondriver.tod.settings.LogCleanPreference
        android:defaultValue="0"
        android:dialogTitle="@string/dialog_title_log_clean"
        android:entries="@array/log_clean"
        android:entryValues="@array/log_clean_values"
        android:key="log_clean_preference"
        android:summary="@string/summary_log_clean_preference"
        android:title="@string/title_log_clean_preference" />

1st, Create a change listener:

private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            String stringValue = value.toString();

            if (preference instanceof ListPreference) {
                // For list preferences, look up the correct display value in
                // the preference's 'entries' list.
                ListPreference listPreference = (ListPreference) preference;
                int index = listPreference.findIndexOfValue(stringValue);

                // Set the summary to reflect the new value.
                preference
                        .setSummary(index >= 0 ? listPreference.getEntries()[index]
                                : null);

            }
            return true;
        }
    };

2nd, Bind preference to its value:

// Set the listener to watch for value changes.
        preference
                .setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

        // Trigger the listener immediately with the preference's
        // current value.
        sBindPreferenceSummaryToValueListener.onPreferenceChange(
                preference,
                PreferenceManager.getDefaultSharedPreferences(
                        preference.getContext()).getString(preference.getKey(),
                        ""));

3rd, in the 1st step you can insert the code to launch you dialog with the if condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM