shared preferences保存、显示用户名和密码

来源:互联网 发布:程序监控软件 编辑:程序博客网 时间:2024/05/29 12:05

用shared preferences方法做一个登陆界面

public class PreActivity extends Activity {



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pre);
SharedPreferences prefs = getSharedPreferences(Common.AA,MODE_PRIVATE);
String username = prefs.getString("username","");
//获回shared prefrences数据
String password = prefs.getString("password","");
EditText tv=(EditText) findViewById (R.id.username);
//取得文本框
tv.setText(username);
//将取得的shared prefrences数据设置到文本框中
EditText tv2=(EditText) findViewById (R.id.password);
tv2.setText(password);


//
//添加按钮事件
//

Button startButton = (Button) findViewById(R.id.button1);
startButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
EditText tv = (EditText) findViewById(R.id.username);
//根据id获取文本框
String usr = tv.getText().toString();
//取得文本框中的值
EditText tv2=(EditText) findViewById (R.id.password);
String psw=tv2.getText().toString();
SharedPreferences prefs = getSharedPreferences(Common.AA,MODE_PRIVATE);
Editor mEditor = prefs.edit();
mEditor.putString("username",usr );
//将文本框中的值写入XML文件中
mEditor.putString("password",psw);
mEditor.commit();
//提交

Toast.makeText(PreActivity.this, R.string.succsess, Toast.LENGTH_LONG).show();
//提示操作成功
}
});

}



以下是XML

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="@string/username" />


    <EditText
        android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView1"
        android:layout_marginLeft="60dp"
        android:layout_toRightOf="@+id/textView1"
        android:ems="10"
        android:inputType="text|number" >


        <requestFocus />
    </EditText>


    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignRight="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="62dp"
        android:text="@string/password" />


    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_centerVertical="true"
        android:text="@string/Button" />


    <EditText
        android:id="@+id/password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView3"
        android:layout_alignLeft="@+id/username"
        android:ems="10"
        android:inputType="textPassword" />