先看下效果图:
该界面的布局文件为:
- <?xml version="1.0" encoding="utf-8"?>
- <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:stretchColumns="1"
- android:layout_marginLeft="10dp"
- android:layout_marginRight="10dp"
- android:layout_marginTop="10dp"
- tools:context="xjtu.com.rememberpwd.MainActivity">
- <TableRow>
- <TextView android:text="账号:"
- android:paddingLeft="30dp"/>
- <EditText android:id="@+id/username"
- android:background="@drawable/et_shape"/>
- </TableRow>
- <TableRow android:layout_marginTop="10dp">
- <TextView android:text="密码:"
- android:paddingLeft="30dp"/>
- <EditText android:id="@+id/password"
- android:background="@drawable/et_shape"
- android:inputType="textPassword"/>
- </TableRow>
- <TableRow android:layout_marginTop="10dp">
- <CheckBox android:id="@+id/chk"
- android:text="记住密码"/>
- <Button android:id="@+id/btn_login"
- android:background="@drawable/btn_shape"
- android:text="登录"/>
- </TableRow>
- </TableLayout>
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- import android.widget.CheckBox;
- import android.widget.EditText;
- public class MainActivity extends AppCompatActivity {
- private Button btn_login;
- private EditText username,password;
- private CheckBox chk;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- initView();
- restoreInfo();
- }
- private void initView(){
- btn_login=(Button)findViewById(R.id.btn_login);
- username=(EditText)findViewById(R.id.username);
- password=(EditText)findViewById(R.id.password);
- chk=(CheckBox)findViewById(R.id.chk);
- btn_login.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (chk.isChecked()){
- String usr=username.getText().toString();
- String pwd=password.getText().toString();
- memInfo(usr,pwd);
- }else{
- SharedPreferences.Editor et=getSharedPreferences("data",0).edit();
- et.clear();
- et.commit();
- }
- Intent intent=new Intent(MainActivity.this,LoginSuccess.class);
- startActivity(intent);
- }
- });
- }
- private void memInfo(String usr,String pwd){
- SharedPreferences.Editor editor=getSharedPreferences("data",0).edit();
- editor.putString("username",usr);
- editor.putString("password",pwd);
- editor.commit();
- }
- private void restoreInfo(){
- SharedPreferences sp=getSharedPreferences("data",0);
- username.setText(sp.getString("username",""));
- password.setText(sp.getString("password",""));
- }
- }