简体   繁体   中英

Android PreferenceActivity and dialog fragments

The app I am developing has an activity that extends SherlockFragmentActivity . I would like to use the preferences api in order to easily add preferences to the activity. Since I would like to support api level 8 and above, I have to extend the activity from the class SherlockPreferenceActivity .

The problem is that the activity needs to show a dialog. The dialog extends SherlockDialogFragment . The show() method of the dialog needs two parameters: a FragmentManager object and a String tag.
In order to get the FragmentManager object, i used to call the getSupportFragmentManager() method of the activity. This method is missing from SherlockPreferenceActivity . I tried to use getFragmentManager() but Eclipse says that

The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (FragmentManager, String)

How can I show the dialog fragment from SherlockPreferenceActivity ?

You should use Shared Preferences rather than using the PreferenceActivity . Declare these references in a separate helper class rather than extending it to an Activity.This gives you the flexibility of creating a custom layout.

Example:

public class SharePrefManager {
    // Shared Preferences
    SharedPreferences pref;

    // Editor for Shared preferences
    Editor editor;

    // Context
    Context _context;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Sharedpref file name
    private static final String PREF_NAME = "selfhelppref";

    //Your configurable fields
    public static final String KEY_PREF1 = "pref1";
    public static final String KEY_PREF2 = "pref2";
    public static final String KEY_PREF3 = "pref3";


    public SharePrefManager(Context context){
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    //Setter function for configurable field
    public void setPref(String key, String value){
       editor.putString(key, value);
    }

   //Getter function for configurable field
   public String getPref(String key){
           return editor.getString(key);
   }
}

Referencing on your activity

SharePrefManager SM = new SharePrefManager(this);
SM.setPref(SM.KEY_PREF1, "name");
String value = SM.getPref(SM.KEY_PREF1);

Try using SherlockDialogFragment.getSherlockActivity().getSupportFragmentManager() .

Example: mySherlockDialogFragment.show(mySherlockDialogFragment.getSherlockActivity().getSupportFragmentManager(), "my_tag");

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