このエントリーをはてなブックマークに追加
>> 開発>> APIサンプル

App - Activity - Presistence State

Presistence State

テキストを自動的に保存・読み込み カーソル位置も保存

Java

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.save_restore_state);

//下側のテキストは固定
        ((TextView)findViewById(R.id.msg)).setText(R.string.persistent_msg);

       //上側のEditを取得
        mSaved = (EditText)findViewById(R.id.saved);
    }


//読み込み
    protected void onResume() {
        super.onResume();

        SharedPreferences prefs = getPreferences(0); 
        String restoredText = prefs.getString("text", null);
        if (restoredText != null) {
            mSaved.setText(restoredText, TextView.BufferType.EDITABLE);

            int selectionStart = prefs.getInt("selection-start", -1);
            int selectionEnd = prefs.getInt("selection-end", -1);
            if (selectionStart != -1 && selectionEnd != -1) {
                mSaved.setSelection(selectionStart, selectionEnd);
            }
        }
    }


//保存
    protected void onPause() {
        super.onPause();

        SharedPreferences.Editor editor = getPreferences(0).edit();
        editor.putString("text", mSaved.getText().toString());
        editor.putInt("selection-start", mSaved.getSelectionStart());
        editor.putInt("selection-end", mSaved.getSelectionEnd());
        editor.commit();
    }

    private EditText mSaved;
}

Layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

    <TextView android:id="@+id/msg"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip" />

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:text="@string/saves_state"/>

    <EditText android:id="@+id/saved"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/green"
        android:text="@string/initial_text"
        android:freezesText="true">
        <requestFocus />
    </EditText>

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingTop="8dip"
        android:paddingBottom="4dip"
        android:text="@string/no_saves_state"/>

    <EditText 
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/red"
        android:text="@string/initial_text">
    </EditText>

</LinearLayout>

関連サイト
www.akjava.com | github.com/akjava
Copyright (C) 2008-20014 Aki Miyazakion Google+ All Rights Reserved.