Tutorial: Preferences
We will continue using the example project "de.vogella.android.social".
Create an Android XML resource "preferences.xml" of type "PreferenceScreen".
Open the file via right-mouse click and
→ . Press Add, add a "PreferenceCategory" and add two preferences "EditTextPreferences" to this category : "User" and "Password".
You can also maintain other properties to EditTextField, e.g. the inputMethod. Add for example the following attribute to the XML definition of your password to make the input quoted with *
.
android:inputType="textPassword"
Create the class "MyPreferencesActivity" with extends PreferenceActivity. This activity will load the "preference.xml" and will allow to maintain the values.
package de.vogella.android.socialapp; import android.os.Bundle; import android.preference.PreferenceActivity; public class MyPreferencesActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } }
To make this class available as an activity for Android you need to register it in your "AndroidManifest.xml" file. Select "AndroidManifest.xml" and the tab "Application". Scroll to the botton of the view and add your new activity via the "Add" button.
To make use of our new preference activity and the preference values we adjust the "OverviewActivity". The first button will show the current values of the preferences via a Toast and the second button will revert the maintained user name to demonstrate how you could change the preferences via code.
package de.vogella.android.socialapp; import android.app.Activity; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class OverviewActivity extends Activity { SharedPreferences preferences; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.Button01); // Initialize preferences preferences = PreferenceManager.getDefaultSharedPreferences(this); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { String username = preferences.getString("username", "n/a"); String password = preferences.getString("password", "n/a"); showPrefs(username, password); } }); Button buttonChangePreferences = (Button) findViewById(R.id.Button02); buttonChangePreferences.setOnClickListener(new OnClickListener() { public void onClick(View v) { updatePreferenceValue(); } }); } private void showPrefs(String username, String password){ Toast.makeText( OverviewActivity.this, "Input: " + username + " and password: " + password, Toast.LENGTH_LONG).show(); } private void updatePreferenceValue(){ Editor edit = preferences.edit(); String username = preferences.getString("username", "n/a"); // We will just revert the current user name and save again StringBuffer buffer = new StringBuffer(); for (int i = username.length() - 1; i >= 0; i--) { buffer.append(username.charAt(i)); } edit.putString("username", buffer.toString()); edit.commit(); // A toast is a view containing a quick little message for the // user. We give a little feedback Toast.makeText(OverviewActivity.this, "Reverted string sequence of user name.", Toast.LENGTH_LONG).show(); }
To open the new preference activity we will use the method onOptionsItemSelected(). Even though we currently have only one option in our menu we use a switch to be ready for several new menu entries. To see the current values of the preferences we define a button and use the class "PreferenceManager" to get the sharedPreferences.
@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mainmenu, menu); return true; } // This method is called once the menu is selected @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // We have only one menu option case R.id.preferences: // Launch Preference activity Intent i = new Intent(OverviewActivity.this, MyPreferencesActivity.class); startActivity(i); // Some feedback to the user Toast.makeText(OverviewActivity.this, "Enter your user credentials.", Toast.LENGTH_LONG).show(); break; } return true; }
Run your application. Press the "menu" hardware button and then select your menu item "Preferences". You should be able to enter your user settings then press the back hardware button to return to your main activity. The saved values should be displayed in a small message windows (Toast) if you press your first button. If you press the second button the username should be reversed.
We have already used a "Toast" which is a small message window which does not take the focus. In this chapter we will use the class "AlertDialog". AlertDialog is used to open a dialog from our activity. This modal dialog gets the focus until the user closes it.
An instance of this class can be created by the builder pattern, e.g. you can chain your method calls.
You should always open a dialog from the class onCreateDialog(int) as the Android system manages the dialog in this case for you. This method is automatically called by Android if you call showDialog(int).
Create a new Android project "de.vogella.android.alertdialog" with the activity "ShowMyDialog". Maintain the following layout for "main.xml".
Change the code of your activity to the following.
package de.vogella.android.alertdialog; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Toast; public class ShowMyDialog extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void openMyDialog(View view) { showDialog(10); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case 10: // Create out AlterDialog Builder builder = new AlertDialog.Builder(this); builder.setMessage("This will end the activity"); builder.setCancelable(true); builder.setPositiveButton("I agree", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ShowMyDialog.this.finish(); } }); builder.setNegativeButton("No, no", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(),"Activity will continue",Toast.LENGTH_LONG).show(); } }); AlertDialog dialog = builder.create(); dialog.show(); } return super.onCreateDialog(id); } }
If you run your application and click your button you should see your dialog.
More on dialogs can be found on Android Dialogs standard documentation.
No comments:
Post a Comment