代码块:
public class MainActivity extends AppCompatActivity {
private EditText et_name,et_pass;
SharedPreferences share;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name=(EditText)findViewById(R.id.et_name);
et_pass=(EditText)findViewById(R.id.et_pass);
share=getSharedPreferences("login",MODE_PRIVATE);
String name=share.getString("name","");
String pass=share.getString("pass","");
if(!name.isEmpty() && !pass.isEmpty()){
Intent intent=new Intent(this,Main2Activity.class);
startActivity(intent);
}
}
//登录
public void login(View view){
String name = et_name.getText().toString();
String pass = et_pass.getText().toString();
//从SharedPreferences里面获取一个可编辑对象
SharedPreferences.Editor editor=share.edit();
editor.putString("name",name);
editor.putString("pass",pass);
editor.commit();//提交
}
}
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="org.frxm.day05_sharepre.MainActivity">
<EditText
android:id="@+id/et_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="请输入用户名"/>
<EditText
android:id="@+id/et_pass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="请输入密码"/>
<Button
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="login"
android:text="登录" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="org.frxm.day05_sharepre.Main2Activity">
</RelativeLayout>