Powered By Blogger

2012年5月12日 星期六

Android開發手札-儲存當前畫面文字

此專案開發常應用於簡訊及各個文字輸入儲存,如寫到一半須儲存避免資料關閉後消失的方法。在此分享最簡單的寫法及應用。



--------------------------------------------mian.java--------------------------------------------


public class main extends Activity {
    public static final String SETTING_FILE = "SETTING_File";
    //定義SharedPreferences內容檔名
    public static final String NAME_MSG = "Name_Msg";   
    //定義字串變數-1
   
private EditText mEditText01;  
private Button toastButton;
 /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,        WindowManager.LayoutParams.FLAG_FULLSCREEN);

       setContentView(R.layout.main);
       
        mEditText01 = (EditText)findViewById(R.id.editText1);
        SharedPreferences settings = getSharedPreferences(SETTING_FILE, 0);
        String name_msg = settings.getString(NAME_MSG, "");
        mEditText01.setText(name_msg);
        mEditText01.setTextColor(Color.RED);
        toastButton = (Button) findViewById(R.id.button1);
                   toastButton.setOnClickListener(new Button.OnClickListener() {
                   public void onClick(View view) {
                   Toast.makeText(view.getContext(),
                   "已儲存完畢!",   
                   Toast.LENGTH_LONG).show();
                   SharedPreferences settings = getSharedPreferences(SETTING_FILE, 0);
                   settings.edit()
                  .putString(NAME_MSG, mEditText01.getText().toString())
                  .commit();
       }
    });
  }   
}


--------------------------------------------mian.xml--------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android" android:baselineAligned="false"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical">
 <EditText android:hint="請輸入筆記" 
android:id="@+id/editText1"
android:layout_width="fill_parent"
 android:layout_height="350dip">
</EditText>
 <LinearLayout android:layout_height="wrap_content"
 android:id="@+id/linearLayout1"
 android:layout_width="fill_parent">
 <Button android:layout_height="wrap_content"
android:id="@+id/button1" android:text="儲存"
android:layout_width="fill_parent"
android:layout_gravity="center">
</Button>
    </LinearLayout>
</LinearLayout>


--------------------------------------------成品展示--------------------------------------------

輸入玩文字後,按下儲存後,關閉專案,下次執行時就會出現先前已打的文字。






沒有留言:

張貼留言