小组任务作业
1.布局代码
<?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:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="请输入姓名:"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="30sp"
android:gravity="center"/>
<EditText
android:id="@+id/name"
android:layout_width="0dp"
android:textSize="25sp"
android:layout_height="wrap_content"
android:layout_weight="4"/>
</LinearLayout>
<TextView
android:text="请输入年龄:"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="30sp"
android:gravity="center"/>
<EditText
android:id="@+id/year"
android:layout_width="0dp"
android:textSize="25sp"
android:layout_height="wrap_content"
android:layout_weight="4"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/write"
android:text="写入"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="25sp"
android:onClick="onClick"/>
<Button
android:id="@+id/read"
android:text="读取"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="25sp"
android:onClick="onClick"/>
</LinearLayout>
2.java代码
public class MainActivity extends AppCompatActivity {
private EditText name;
private EditText year;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
year = (EditText) findViewById(R.id.year);
}
public void onClick(View view) {
switch (view.getId()){
case R.id.write:
String name = name.getText().toString();
String year = year.getText().toString();
if(saveToPrefs(name,year)){
Toast.makeText(MainActivity.this,"写入完毕",Toast.LENGTH_SHORT).show();
}
break;
case R.id.read:
readFromPrefs();
break;
}
}
private void readFromPrefs() {
SharedPreferences preferences = getSharedPreferences("customer.txt",MODE_PRIVATE);
String name=preferences.getString("name","");
String year=preferences.getString("year","");
name.setText(name);
year.setText(year);
}
private boolean saveToPrefs(String name, String year){
SharedPreferences preferences = MainActivity.this.getSharedPreferences("customer.txt",MODE_PRIVATE);
SharedPreferences.Editor editor =preferences.edit();
editor.putString("name",name);
editor.putString("year",year);
editor.commit();
return true;
}
}