SharedPreferences, use xml The file holds the user's preferences , Is a lightweight storage class .

design sketch :

Code :

activity_main

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" tools:context=".MainActivity">
<TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/Hello_World" />
</LinearLayout>

activity_settings

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:name="com.example.admin.sharedpreferences.SettingsActivity$preferenceFragment" android:id="@+id/preference"/>
menu.menu

<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/menu_settings" android:title="@string/menu_title" app:showAsAction="never"/></menu>
 

arrays


<?xml version="1.0" encoding="utf-8"?><resources> <string-array name="color_show"> <item>@string/black</item> <item>@string/red</item> <item>@string/blue</item> <item>@string/green</item> </string-array></resources>

preferences_settings

<?xml version="1.0" encoding="utf-8"?><PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference android:title="@string/CheckBoxPreference_title" android:defaultValue="false" android:summaryOn="@string/CheckBoxPreference_summaryOn" android:summaryOff="@string/CheckBceoxPreferen_summaryOff" android:key="@string/CheckBceoxPreferen_key"/>
<EditTextPreference android:title="@string/EditTextPreference_title" android:defaultValue="@string/EditTextPreference_defaultValue" android:inputType="numberDecimal" android:selectAllOnFocus="true" android:key="@string/EditTextPreference_key"/>
<ListPreference android:title="@string/ListPreference_title" android:defaultValue="@string/ListPreference_defaultValue" android:entries="@array/color_show" android:entryValues="@array/color_show" android:key="@string/ListPreference_key"/></PreferenceScreen>
 
AndroidMainFest
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.admin.sharedpreferences">
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
<activity android:name=".SettingsActivity" android:parentActivityName=".MainActivity"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity"/> </activity> </application>
</manifest>
MainActivity.java

package com.example.admin.sharedpreferences;
import android.content.Intent;import android.content.SharedPreferences;import android.graphics.Color;import android.preference.PreferenceManager;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textview); }
@Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return super.onCreateOptionsMenu(menu); }
@Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.menu_settings: Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); break; } return true; }
@Override protected void onStart() { super.onStart(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
if (sharedPreferences.getBoolean(getString(R.string.CheckBceoxPreferen_key), false)) { textView.setText(R.string.Bye); }
String colorText = sharedPreferences.getString(getString(R.string.ListPreference_key), getString(R.string.ListPreference_defaultValue)); String[] color_array = getResources().getStringArray(R.array.color_show);
for (int i = 0; i < color_array.length; i++) {
if (color_array[i] .equals(colorText)){ setTextColor(i); break; } }
String sizeText = sharedPreferences.getString(getString(R.string.EditTextPreference_key), getString(R.string.EditTextPreference_defaultValue)); int size = Integer.parseInt(sizeText); textView.setTextSize(size); }
public void setTextColor(int number) { switch (number) { default: textView.setTextColor(Color.BLACK); case 0: textView.setTextColor(Color.BLACK); break; case 1: textView.setTextColor(Color.RED); break; case 2: textView.setTextColor(Color.BLUE); break; case 3: textView.setTextColor(Color.GREEN); break;
} }}
SettingsActivity.java

package com.example.admin.sharedpreferences;
import android.content.SharedPreferences;import android.os.Bundle;import android.preference.ListPreference;import android.preference.Preference;import android.preference.PreferenceFragment;import android.preference.PreferenceManager;import android.support.v4.app.NavUtils;import android.support.v7.app.AppCompatActivity;
public class SettingsActivity extends AppCompatActivity { @Override public void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); }
@Override public void onBackPressed() { super.onBackPressed(); NavUtils.navigateUpFromSameTask(this); }
public static class preferenceFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener {
@Override public void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences_settings); Preference preference_size = findPreference(getString(R.string.EditTextPreference_key)); preferenceSummary(preference_size); Preference preference_color = findPreference(getString(R.string.ListPreference_key)); preferenceSummary(preference_color); }
@Override public boolean onPreferenceChange(Preference preference, Object newValue) { String value=String.valueOf(newValue); if (preference instanceof ListPreference){ ListPreference listPreference=(ListPreference) preference; int index=listPreference.findIndexOfValue(value); if (index >=0){ CharSequence[] text=listPreference.getEntries(); preference.setSummary(text[index]); } }else { preference.setSummary(value); } return true; }
public void preferenceSummary(Preference preference) { preference.setOnPreferenceChangeListener(this ); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(preference.getContext()); String text = sharedPreferences.getString(preference.getKey(), ""); onPreferenceChange(preference,text); } }
}
 
github Project source code : https://github.com/NeoWu55/Android-Sharedpreferences

SharedPreferences More articles on the use of classes

  1. Android learning SharedPreferences class

    SharedPreferences class android.content.SharedPreferences Class summary : Access and modification by function getSharedPreferences(String,int) return ...

  2. 【Android】19.1 SharedPreferences class

    classification :C#.Android.VS2015: Date of creation :2016-03-05 One . brief introduction SharedPreferences: Simple shared storage preferences . In fact, it is to use encrypted internal files to save a series of files that all pages can access “n ...

  3. Android SharedPreferences The use of the class

    package com.lidaochen.phonecall; import android.content.Intent; import android.content.SharedPrefere ...

  4. Android Data storage mode --SharedPreferences

    Android There are four ways to store data :SharedPreferences. Store to file .SQLite database . content provider (Content provider). Storage to a network server . This article mainly introduces Share ...

  5. Android—— Save the configuration file SharedPreferences Data storage

    Most of the time, the software we develop needs to provide users with software parameter setting function , For example, we often use QQ, Users can set whether strangers are allowed to add themselves as friends . For saving software configuration parameters , If it is window Software usually we use ini Keep the file , If ...

  6. SharedPreferences Detailed explanation

    When we develop software , It is often necessary to provide users with software parameter setting function , For example, we often use wechat , Users can set whether strangers are allowed to add themselves as friends . For saving software configuration parameters , If it's in window We usually use ini Keep the file ...

  7. Use SharedPreferences Data storage

    Use SharedPreferences Data storage Most of the time, the software we develop needs to provide users with software parameter setting function , For example, we often use QQ, Users can set whether strangers are allowed to add themselves as friends . For saving software configuration parameters , If it is w ...

  8. android Road of development 11( use SharedPreferences Store the data )

    Android The platform provides us with a SharedPreferences class , actually SharedPreferences What we're dealing with is a key-value( Key value pair ), It is A lightweight storage class , It is especially suitable for preserving soft ...

  9. Android One of the ways of data storage SharedPreferences

    Android The platform provides us with a SharedPreferences class , It's a lightweight storage class , Especially suitable for saving software configuration parameters . Use SharedPreferences Save the data , Behind it is the use of xml Number of files stored ...

Random recommendation

  1. mongodb Some basic operations

    1. List all databases >show dbs   2. Using a database >use memo   3. Lists the... Of the current database collections >show collections   4. Display the current ...

  2. Servlet &amp; JSP - The difference between forwarding and redirection

    Reprinted from :http://blog.csdn.net/kobejayandy/article/details/13762043 forward The principle of forwarding , This can be shown in the figure below : The browser's request is sent to the component 1, Components ...

  3. c - Output 101 to 200 The prime between .

    #include <stdio.h> #include <math.h> // Judge 101-200 How many primes are there between , And output all prime numbers . int main(void) { , e ...

  4. install Oracle10g on RedHat as 4 64bit( pick )

    One . Configuration before installation 1. modify RH edition vi /etc/redhat-release Red Hat Enterprise Linux AS release 3 (Taroon Update 3) 2. ...

  5. C/S ASP.NET Page value summary

    One . QueryString It's a very simple way to transfer values , He can display the transmitted value in the address bar of the browser . If it is to pass one or more values with low security requirements or simple structure , You can use this method . But for passing arrays or objects , No ...

  6. js Calculate two time differences

    /* * Calculate the number of days between two dates * BeginDate: Text box for start date , The format is :2012-01-01* EndDate: Text box for end date , The format is :2012-01-02* Returns the number of days between two dates * Tune ...

  7. Use Alibaba cloud integration package to quickly build LAMP+FTP course

    LAMP Integration package installation steps 1. Download the development integration package Download the latest version of Alibaba cloud market WEB Develop integration packages ( contains Apache.Mysql.PHP.vsftpd) #Linux Instructions wget http://gongdan. ...

  8. Kali Learning notes 20: Buffer overflow experimental environment preparation

    In previous blogs : I introduced OpenVAS and Nessus These two powerful automated vulnerability scanners however , In the field of computer, there is a kind called 0day Loophole : It's not open. It's in the hands of some people that , these 0day How is the vulnerability discovered ? continue with ...

  9. JMeter3.0 post Parameters /BeanShell Chinese code scrambling

    In use JMeter, stay http Requested Body Data or BeanShell In Chinese , Why is it all garbled — It's all boxes with a question mark in the middle . And the font is very small , It's hard to see , The random code phenomenon is shown in the figure below :

  10. PHP On the parameter of function

    Maybe I used to write too standard programs , Today I found a PHP The number of function parameters , The function defined has three parameters , But when using the function, four parameters were passed , What's more, the program runs without errors , Not even a warning . So we rely on search engines and PHP Check the documents carefully ...