SharedPreferences的制作

来来来,先看效果。

布局还是那么熟悉

<EditText
android:id="@+id/yf_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/edit1"/>



<EditText
android:id="@+id/yf_age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/edit2"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">



<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_weight="1"
style="@style/button1"
android:onClick="onClick"
android:id="@+id/yf_button1"/>

<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_weight="1"
style="@style/button2"
android:onClick="onClick"
android:id="@+id/yf_button2"/>

</LinearLayout>

</LinearLayout>

 布局大概是这个样子的

做的还是可以的

package hello.xingxibaocunduqu;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
private EditText etname, etage;
private String name, age;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etname = (EditText) findViewById(R.id.name);
etage = (EditText) findViewById(R.id.age);
}

public void onClick(View view) {
switch (view.getId()) {
case R.id.xieru:
name = etname.getText().toString();
age = etage.getText().toString();
save(name,age);
break;
case R.id.duqu:
readPrefs();
break;
}
}

private void save(String name, String age) {
SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
editor.putString("name", name);
editor.putString("age",age);
editor.commit();
editor.clear();
Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();
}

private void readPrefs() {
SharedPreferences prefs = getSharedPreferences("data", MODE_PRIVATE);
String username = prefs.getString("name", "");
String userage = prefs.getString("age", "");
Toast.makeText(MainActivity.this, "姓名是:"+username+"年龄是:"+userage, Toast.LENGTH_LONG).show();
}
}
然后就是代码的实现
问我为什么这么简单
我才发现要交作业
然后时间不多了
所以就
还是可以的

 

posted @ 2017-05-09 23:51  要加伟哥  阅读(129)  评论(0编辑  收藏  举报