2. MainActivity.java
package org.me.android_preference;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText nameEditText;
private Button saveButton;
private Button restoreButton;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
nameEditText = (EditText) findViewById(R.id.nameEditText);
saveButton = (Button) findViewById(R.id.saveButton);
restoreButton = (Button) findViewById(R.id.restoreButton);
saveButton.setOnClickListener(saveClickListener);
restoreButton.setOnClickListener(restoreClickListener);
}
//按下Save按鈕
private Button.OnClickListener saveClickListener = new Button.OnClickListener() {
public void onClick(View arg0) {
//取得SharedPreference設定("Preference"為設定檔的名稱)
SharedPreferences settings = getSharedPreferences("Preference", 0);
//置入name屬性的字串
settings.edit().putString("name", nameEditText.getText().toString()).commit();
}
};
//按下Restore按鈕
private Button.OnClickListener restoreClickListener = new Button.OnClickListener() {
public void onClick(View arg0) {
//取得SharedPreference設定("Preference"為設定檔的名稱)
SharedPreferences settings = getSharedPreferences("Preference", 0);
//取出name屬性的字串
String name = settings.getString("name", "");
nameEditText.setText(name);
}
};
}
3. main.xml(Layout)
<?xml version="1.0" encoding="utf-8"?> <AbsoluteLayout android:id="@+id/widget0" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" > <TextView android:id="@+id/nameView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name:" android:layout_x="22px" android:layout_y="34px" > </TextView> <EditText android:id="@+id/nameEditText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:layout_x="90px" android:layout_y="20px" > </EditText> <Button android:id="@+id/saveButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Save" android:layout_x="20px" android:layout_y="86px" > </Button> <Button android:id="@+id/restoreButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Restore" android:layout_x="98px" android:layout_y="84px" > </Button> </AbsoluteLayout>
4. 執行之後的畫面。(按下Store將Name的值儲存在偏好設定,按下Restore會將儲存在偏好設定的值取回)



沒有留言:
張貼留言