Wednesday, September 21, 2011

Android - Accessing Your Preference From Hardware Menu Button


1) Create New XML File By Clicking "File->New->Other->Android XML File.
2) In Newly Open Dialog Box:
   a) File = Name of Your Preference File Name
   b) "In What type Of Resource would you like to create?" Select "PREFERENCE"
   c) Don't Change The Folder Path
   d) "In Select the root element for XML File" Select "PREFERENCESCREEN"
   e) Click Finish.

3) Select The Type of Preference You want to add. All with very good exmaples are shown here
   http://www.kaloer.com/android-preferences

4) In "AndroidManifest.xml" add the following segment
   <activity
        android:name=".Name_of_your_preference_file">
   </activity>

5) Add New Activity which extends from PreferenceAcivity
   *To know how to add new activity take a look here
    http://codersapprentice.blogspot.com/2011/09/android-easiest-way-to-add-new-activity.html

6) In OnCreate function of the newly created Activity Add the following lines
   
    addPreferencesFromResource(R.xml.mypeference);//Your Preference XML Resource
    PreferenceManager.setDefaultValues(ApplicationPreference.this, R.xml.mypeference, false);//To Set Default Values

7) To Call Preference Screen From Hardware Menu Button Add the following code on the activity from which you want to call the preference:
   @Override
    public boolean onKeyDown(int keycode, KeyEvent event)
    {
    if(keycode == KeyEvent.KEYCODE_MENU)
    {    
    Intent settingsActivity = new Intent(getApplicationContext(),ApplicationPreference.class);
    startActivity(settingsActivity);
    }
    return super.onKeyDown(keycode,event);
    }

No comments:

Post a Comment