布局文件:
<?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:layout_width="match_parent" android:layout_height="match_parent" tools:context=".SharedPreferencesActivity" android:orientation="vertical"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入用户名" android:id="@+id/user" android:textSize="20sp"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入密码" android:textSize="20sp" android:id="@+id/pwd"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:id="@+id/ll"> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="记住密码" android:id="@+id/c1" /> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="自动登陆" android:id="@+id/c2"/> </LinearLayout> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/save" android:text="保存" /> </LinearLayout>跳转界面后的代码:
package com.jerehedu.jereduch10; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Switch; import android.widget.TextView; public class SeetingsActivity extends AppCompatActivity { private Switch st1,st2; private Button saves; private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_seetings); st1= (Switch) findViewById(R.id.st1); st2= (Switch) findViewById(R.id.st2); saves= (Button) findViewById(R.id.saves); final TextView showUser= (TextView) findViewById(R.id.showUser); sp=getSharedPreferences("userInfo",MODE_PRIVATE); saves.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences.Editor editor = sp.edit(); editor.putBoolean("c11",st1.isChecked()); editor.putBoolean("c21", st2.isChecked()); editor.commit(); Intent intent=new Intent(getBaseContext(),SharedPreferencesActivity.class); startActivity(intent); } }); } @Override protected void onStart() { super.onStart(); sp=getSharedPreferences("userInfo",MODE_PRIVATE); Boolean c11=sp.getBoolean("c11",false); Boolean c21=sp.getBoolean("c21",false); st1.setChecked(c11); st2.setChecked(c21); } }运行结果如下:
点击保存按钮:
跳转画面至:
随后更改:记住密码与自动登陆的状态
接着在返回,主页面的记住密码以及自动登陆的状态就会发生变化,从而实现二者的联动。实现数据的保存。
