確定這裏你已經工作,測試代碼
notes.java(src\izzy\n\notes.java
)
package izzy.n;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
// actually you should name the class "Notes" since it's convention
// but it would proably cause errors since you have to rename the file then.
public class notes extends Activity {
public static final String DEFAULT_TEXT = "Write some text here";
public static final String PREFS_KEY_TEXT = "text";
public static final String PREFS_NAME = "MyPrefsFile";
private EditText mEditText;
/**
* Loads the text from SharedPreferences
*/
private String loadText() {
SharedPreferences settings = getSharedPreferences(notes.PREFS_NAME,
Context.MODE_PRIVATE);
return settings.getString(notes.PREFS_KEY_TEXT, notes.DEFAULT_TEXT);
}
/**
* Saves text to SharedPreferences
*/
private void saveText(String text) {
SharedPreferences settings = getSharedPreferences(notes.PREFS_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(notes.PREFS_KEY_TEXT, text);
editor.commit();
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes);
// when you click on the button the app will exit
// you kind of don't need such a button :)
Button wg = (Button) findViewById(R.id.exit_button);
wg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
mEditText = (EditText) findViewById(R.id.edit_text);
String savedText = loadText();
mEditText.setText(savedText);
// put the cursor to the end.
mEditText.setSelection(savedText.length());
}
@Override
protected void onStop() {
super.onStop();
saveText(mEditText.getText().toString());
}
}
notes.xml(res\layout\notes.xml
)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/exit_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Exit" />
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="0dp"
android:gravity="top"
android:layout_weight="1"
android:hint="Enter Text here"
android:inputType="textMultiLine" />
</LinearLayout>
你得到什麼
![how it looks](https://i.stack.imgur.com/3gk6T.png)
PS:你也許應該開始讀一些基本的Java教程因爲你似乎有基礎:)
的問題,如果你'完成()'你告訴Android,你的應用不應該被恢復。也沒有真正保存文本的代碼。看到[SharedPreferences](http://developer.android.com/reference/android/content/SharedPreferences.html)左右 – zapl 2012-03-17 14:10:29
所以我把它拿出來,並放置super.onRestore()? – user1248404 2012-03-17 14:11:34
你在哪裏保存你的文字? – Deepak 2012-03-17 14:16:51