在TextView中保存滚动位置

时间:2017-11-02 17:10:48

标签: java android scroll textview android-scrollview

我的应用程序包含一系列长文本,我希望用户能够在他们离开该视图时返回到他们的位置。

我已将this answer的代码改编为ListView。第一个Log很好,但第二个没有,这表明state为空。

这是我的StoryBodyActivity:

public class StoryBodyActivity extends AppCompatActivity {

    private TextView storyBodyTextView;
    private ScrollView storyBodyScrollView;
    Parcelable state;

    @Override
    public void onPause() {
        Log.d("pause", "saving listview state @ onPause");
        state = storyBodyTextView.onSaveInstanceState();
        super.onPause();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_story_body);

        Bundle extras = getIntent().getExtras();

        String story = extras.getString("story");

        setTitle(story);

        storyBodyTextView = (TextView) findViewById(R.id.story_body_text_view);
        storyBodyScrollView = (ScrollView) findViewById(R.id.story_body_scroll_view);

        DatabaseHelper db = new DatabaseHelper(this);

        String storyBody = db.getStoryBody(story);

        storyBodyTextView.setText(Html.fromHtml(storyBody));

        if(state != null) {
            Log.d("pause", "trying to restore textview state..");
            storyBodyTextView.onRestoreInstanceState(state);
        }
    }
}

我还需要确保保存每个单独长文本的位置。

这是DatabaseHelper,用于显示数据的来源:

public String getStoryBody(String story) {

        Log.i("test", "hello");

        String storyBody = "";

        // Select all query
        String selectQuery = "SELECT * FROM " + BOOKS + " WHERE title =  '" + story + "'";

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                storyBody = cursor.getString(4);
            } while (cursor.moveToNext());
        }
        return storyBody;
    }

0 个答案:

没有答案