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();//
}
}
}
效果圖如下: