Android 登陆界面及记住用户名密码

下面是LoginActivity类

private static final String PREFS_NAME = "MyUserInfo";

@Override  

    protected void onCreate(Bundle savedInstanceState) {   

        // TODO Auto-generated method stub   

        super.onCreate(savedInstanceState);   

        setContentView(R.layout.login);   

        findViews();

        setListensers();

    }   

private Button submit;

private Button reset; private EditText name;

private EditText password;

private CheckBox saveuserinfo;

private void findViews(){

  name = (EditText)findViewById(R.id.name);

  password = (EditText)findViewById(R.id.password);

  submit = (Button)findViewById(R.id.submit);

  reset = (Button)findViewById(R.id.reset);  saveuserinfo = (CheckBox)findViewById(R.id.saveuserinfo);

}



private void setListensers(){

        LoadUserDate();

  submit.setOnClickListener(sublis);

  reset.setOnClickListener(resetlis);

}



private Button.OnClickListener sublis = new Button.OnClickListener(){

  public void onClick(View v){

   SaveUserDate();

   String namestr = name.getText().toString();

   String passwordstr = password.getText().toString();

   if(namestr==null||namestr.equals("")||passwordstr==null||passwordstr.equals("")){

    Toast.makeText(LoginActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();

   }else{

    Toast.makeText(LoginActivity.this, "您输入的是name:"+namestr+"\npassword:"+passwordstr, Toast.LENGTH_LONG).show();

   }

  }

};

private Button.OnClickListener resetlis = new Button.OnClickListener(){

  public void onClick(View v){

   name.setText("");

   password.setText("");

  }

};



/**

  * 保存用户信息

  */

private void SaveUserDate(){

  //载入配置文件

  SharedPreferences sp = getSharedPreferences(PREFS_NAME, 0);

  //写入配置文件

  Editor spEd = sp.edit();

  if(saveuserinfo.isChecked()){

   spEd.putBoolean("isSave", true);

   spEd.putString("name", name.getText().toString());

   spEd.putString("password", password.getText().toString());

  }else{

   spEd.putBoolean("isSave", false);

   spEd.putString("name", "");

   spEd.putString("password", "");

  }

  spEd.commit();

}



/**

  * 载入已记住的用户信息

  */

private void LoadUserDate(){

  SharedPreferences sp = getSharedPreferences(PREFS_NAME, 0);

  

  if(sp.getBoolean("isSave", false)){

   String username = sp.getString("name", "");

   String userpassword = sp.getString("password", "");

   if(!("".equals(username)&&"".equals(userpassword))){

    name.setText(username);

    password.setText(userpassword);

    saveuserinfo.setChecked(true);

   }

  }

}

 

 

你可能感兴趣的:(android)