Domanda

I have defined a PreferenceScreen in XML, containing several EditTextPreference "objects". I want to catch user input from these fields, but I can't see to figure out how. The answer would seem to lie here, but I'm not gettng it: http://developer.android.com/reference/android/preference/EditTextPreference.html

I'm guessing it's similar to this:

AlertDialog.Builder alert = new AlertDialog.Builder ( this );
final EditText input = new EditText ( this );
    alert.setView ( input );

    alert.setPositiveButton ( "Ok", new DialogInterface.OnClickListener () {
        public void onClick ( DialogInterface dialog, int whichButton ) {
            c.setName ( input.getText ().toString () );
        }
    } );
È stato utile?

Soluzione

Like other Activity, you can use PreferenceScreen as a PreferenceActivity. And its corresponding class looks like below:

public class MyPreferencesActivity extends PreferenceActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      addPreferencesFromResource(R.xml.preferences);// point your xml file
  }
} 

Don't forget to register this class as an activity in your AndroidManifest.xml file.

To show the Preference screen, just call it as a usual Activity as:

Intent i = new Intent(OverviewActivity.this, MyPreferencesActivity.class);
startActivity(i);

And you can access its values as

SharedPreferences  preferences = PreferenceManager.getDefaultSharedPreferences(this);
String username = preferences.getString("your_key", "default_value");

For more reference, Hava a look at http://www.vogella.com/articles/AndroidFileBasedPersistence/article.html#tutorial_preferenceactivity

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top