Android中一共有四种存储方式:
SharedPreferences 为其中的一种,具体还是看代码:
package com.wyl.preferencetest; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import android.os.Build; import android.preference.PreferenceManager; public class MainActivity extends ActionBarActivity { SharedPreferences pref ; String username; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //1 获取到preference的两种方式: // pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); pref = getSharedPreferences("myOwn", MODE_PRIVATE); //2.使pref可编辑,获得一个可编辑对象 Editor editor = pref.edit(); editor.putString("yourname", "wyl"); editor.putInt("age", 26); //3提交编辑,否则不成效的 editor.commit(); editor.putBoolean("flag", true); editor.putBoolean("flag2", true); editor.remove("flag"); editor.commit(); String myname = pref.getString("yourname","yourname"); System.out.println("myname:"+myname); MainActivity.this.username = myname; } public void btnOclick(View v){ if(R.id.btn01==v.getId()){ System.out.println("======"+this.username); // Toast.makeText(MainActivity.this, username+",你登陆成功了", 1000).show();//一定要加.show()方法 Toast.makeText(MainActivity.this, "this is the toast content", Toast.LENGTH_LONG).show();// } } }
效果图如下:
时间: 2024-10-27 13:34:31