Lesson 71. Preferences as a Program Settings. PreferenceActivity

Lesson 71. Preferences as a Program Settings. PreferenceActivity


In this lesson:

– we use Preferences to work with the settings of the application

We have already passed Preferences, used them to store our data, we know the mechanism. Now let’s see how they are used to store the settings of the program. Android provides a special Activity to work with settings – PreferenceActivity. It can read certain xml files and create a settings screen from them.

Let’s create a simple application. On the first screen we will read and display the settings of the program, and on the second we will put them with PreferenceActivity.

You need to come up with some settings. Be it the settings of some messages, namely the ability to enable / disable messages (checkboxes) and the ability to spell out the recipient’s address (text input field).

Let’s create a project:

Project name: P0711_PreferencesSimple
Build Target: Android 2.3.3
Application name: PreferencesSimple
Package name: en.startandroid.develop.p0711preferencessimple
Create Activity: MainActivity

First, let’s create an xml file describing the settings. In the folder really create a folder xml, And in it we create a file pref.xml:



    
    
    
    

Here we have indicated that our settings screen (PreferenceScreen) Will contain a checkbox (CheckBoxPreference) And field (EditTextPreference) To enter a value. parameters: key – save / read key, summary – text-explanation, title – The title. Next we will see what and where it is used.

We create Activity for settings. PrefActivity.java:

package ru.startandroid.develop.p0711preferencessimple;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class PrefActivity extends PreferenceActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.pref);
  }
}

Instead of setContentView, we use the addPreferencesFromResource method, which takes the pref.xml file and creates the installation windows.

Don’t forget to add this Activity to the manifest. There are no features here, as usual.

we draw a screen main.xml:



    
    

One TextView that will read and display application settings.

MainActivity.java:

package ru.startandroid.develop.p0711preferencessimple;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {

  TextView tvInfo;
  SharedPreferences sp;

  /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tvInfo = (TextView) findViewById(R.id.tvInfo);

    // получаем SharedPreferences, которое работает с файлом настроек
    sp = PreferenceManager.getDefaultSharedPreferences(this);
    // полная очистка настроек
    // sp.edit().clear().commit();
  }

  protected void onResume() {
    Boolean notif = sp.getBoolean("notif", false);
    String address = sp.getString("address", "");
    String text = "Notifications are "
        + ((notif) ? "enabled, address = " + address : "disabled");
    tvInfo.setText(text);
    super.onResume();
  }

  public boolean onCreateOptionsMenu(Menu menu) {
    MenuItem mi = menu.add(0, 1, 0, "Preferences");
    mi.setIntent(new Intent(this, PrefActivity.class));
    return super.onCreateOptionsMenu(menu);
  }
}

IN onCreate we find TextView and get the SharedPreferences settings object. He knows us, we worked with him earlier in the lesson on Preferences. The following is a commented code to completely clean the program settings. We do not use it, just in case I indicated, can anyone need.

IN onResume we read the settings from SharedPreferences and display them in TextView. When reading, we use the same keys that were written in the xml file in the attributes key.

IN onCreateOptionsMenu just configure the menu to bring up the settings window. We create a menu item and hang Intent on it – the result is clicked Activity.

Just in case, let me clarify why to use information on the screen here I use onResume, but not onCreate. Because when we go back from the settings screen to the main window, the onCreate of the main window does not work (because the window is already created and hangs in memory) and we will not see any changes. And onResume will work.

We all save and launch the application. We see the following screen:

By default, if the settings are not already specified, we get a false and empty string, as indicated by the getBoolean and getString methods on onResume.

Click menu and go to settings.

What we were pointing to pref.xml the system read and created the installation windows itself. Now we can specify the values ​​we need here and they will be stored immediately without any Save buttons. However, this is the standard behavior of Android settings. I think every one of you has ever dug into the settings and knows it.

Let’s turn on our posts

and write down the addresses

Click OK.

We push the button back, we get to the main screen

which in onResume read the fresh settings and displayed them.

In the next lesson:

– use the list in the settings
– Group settings by screens and categories




Discuss in the forum [48 replies]

Leave a Comment