1. 程式人生 > >SharedPreferences的制作

SharedPreferences的制作

user span onclick mpat ack find .sh ast andro

技術分享技術分享

來來來,先看效果。

布局還是那麽熟悉

<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();
}
}
然後就是代碼的實現
問我為什麽這麽簡單
我才發現要交作業
然後時間不多了
所以就
還是可以的

SharedPreferences的制作