Android [SharedPreference轻量级存储]

丈夫志四海,万里犹比邻。这篇文章主要讲述Android [SharedPreference轻量级存储]相关的知识,希望能为你提供帮助。
SharedPreferencesActivity.java

package com.xdw.a122.data; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.xdw.a122.R; public class SharedPreferencesActivity extends AppCompatActivity { private EditText mEtName; private Button mBtnSave,mBtnShow; private TextView mTvContent; private SharedPreferences mSharedPreferences; private SharedPreferences.Editor mEditor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shared_preferences); mEtName=findViewById(R.id.et_name); mBtnSave=findViewById(R.id.btn_save); mBtnShow=findViewById(R.id.btn_show); mTvContent=findViewById(R.id.tv_show); mSharedPreferences=getSharedPreferences("data",MODE_PRIVATE); //名称和类型 mEditor=mSharedPreferences.edit(); mBtnSave.setOnClickListener(new View.OnClickListener() {//存储 @Override public void onClick(View v) { mEditor.putString("name",mEtName.getText().toString()); //此处写要提交的内容 mEditor.apply(); //or commit(); 存储完成 } }); mBtnShow.setOnClickListener(new View.OnClickListener() {//读取 @Override public void onClick(View v) { mTvContent.setText(mSharedPreferences.getString("name","")); } }); } }

【Android [SharedPreference轻量级存储]】activity_shared_preferences
< ?xml version="1.0" encoding="utf-8"?> < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".data.SharedPreferencesActivity"> < EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="输入内容" /> < Button android:id="@+id/btn_save" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="保存" android:layout_marginTop="10dp"/> < Button android:id="@+id/btn_show" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="显示"/> < TextView android:id="@+id/tv_show" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp"/> < /LinearLayout>

输入内容在 //存储 输入存储内容
并在tv_show显示
mSharedPreferences=getSharedPreferences("data",MODE_PRIVATE); //名称和类型 mEditor=mSharedPreferences.edit();

存储的类型

    推荐阅读