您的位置:首页 > Web前端

SharedPreferences存储——记住用户名和密码

2012-10-15 17:57 309 查看
在我们登陆如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,存储数据)。

输入信息后下次登录时,信息就已经在里面了,如图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: