SharedPreferences存儲——記住用戶名和密碼

在我們登陸如QQ或其他網站時,習慣電腦通過記錄登陸,從而不需要再次輸入用戶名,密碼那麼麻煩。

這種“記憶”性的功能,只要用SharedPreferences進行存儲就完成了!

首先,還是佈局:

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"//垂直分佈(這裏千萬不能漏)
    android:background="#080101"//爲了美觀後來加的背景顏色(顏色可自選)
    android:layout_width="fill_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/padding_medium"
        android:text="用戶名:"
        tools:context=".MainActivity" />

    <EditText
        android:id="@+id/username"
        android:layout_width="fill_parent"
        
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="密碼:" />

    <EditText
        android:id="@+id/password"
        android:password="true"//只有在true的時候,輸入的密碼才能自動以點的形式顯示
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


然後,就是主要方法了:

public class MainActivity extends Activity {
    public static final String SETTING_INFOS="SETTING_Infos";
	private EditText nameText;
	private EditText passwordText;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		SharedPreferences sharedPreferences = getSharedPreferences(
				SETTING_INFOS, Context.MODE_PRIVATE);
		nameText = (EditText) this.findViewById(R.id.username);
		passwordText = (EditText) this.findViewById(R.id.password);
		String name = sharedPreferences.getString("name", "");
		String password = sharedPreferences.getString("password", "");
		if (name != null && !"".equals(name)) {//輸入的用戶名內容不爲空,也不是空格時
			nameText.setText(name);//顯示用戶名
		}
		if (password != null && !"".equals(password)) {
			passwordText.setText(password);
		}
	}

	protected void onStop() {
		super.onStop();
		nameText = (EditText) this.findViewById(R.id.username);
		passwordText = (EditText) this.findViewById(R.id.password);
		String name = nameText.getText().toString();
		String password = passwordText.getText().toString();
		SharedPreferences sharedPreferences = getSharedPreferences(
				SETTING_INFOS, Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();//通過sharedPreferences存儲數據
		editor.putString("name", name);

		editor.putString("password", password);
		editor.commit();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

劃線部分則是核心,用SharedPreferences存儲數據(定義一個SETTING_INFOS,存儲數據)。

輸入信息後下次登錄時,信息就已經在裏面了,如圖:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章