В любом приложении есть настройки по умолчанию, которые можно получить через экземпляр PreferenceManager
и связанный с ним метод getDefaultSharedPreferences(Context)
.
С экземпляром SharedPreference
можно получить значение int любого предпочтение с getInt (String key, int defVal). Предпочтение, которое нас интересует в этом случае, является счетчиком.
В нашем случае мы можем изменить экземпляр SharedPreference
в нашем случае с помощью edit () и использовать putInt(String key, int newVal)
. Мы увеличили счет для наших приложение, которое выступает за пределы приложения и отображается соответствующим образом.
Чтобы продолжить демонстрацию этого, перезапустите и приложение снова, вы заметите, что счет будет увеличиваться каждый раз при перезапуске приложения.
PreferencesDemo.java
Код:
package org.example.preferences;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;
public class PreferencesDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the app's shared preferences
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
// Get the value for the run counter
int counter = app_preferences.getInt("counter", 0);
// Update the TextView
TextView text = (TextView) findViewById(R.id.text);
text.setText("This app has been started " + counter + " times.");
// Increment the counter
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("counter", ++counter);
editor.commit(); // Very important
}
}
main.xml
Код:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>