How to get last ListView state when coming back from Activity
Asked Answered
B

2

5

I have a custom ListView in which I have some TextViews and a few buttons. On clicking every button a new activity opens.
The problem is, let's say if I am currently viewing the 15th ListView item and clicks the button on that which opens new activity. When coming back from an activity the ListView goes back to 1st item but I want it to resume from the view (15th item in this case) where I left on starting a new activity. How can I do that?

I am new to android development so do not know which keywords to search for this problem!
Any help is appreciated :)

Bencher answered 15/6, 2020 at 22:42 Comment(0)
A
4

Try listView.setSelection(15); or listView.smoothScrollToPosition(15);. Just before going to activity 15 save it, so when You go back to MainActivity just call this function with a saved parameter.

Adda answered 15/6, 2020 at 22:53 Comment(0)
P
2

Best way is to restore the whole state manually:

class MainActivity : AppCompatActivity() {
    companion object {
        private const val LIST_STATE_ARG = "SomeCustomString"
    }

    private lateinit var list: ListView

    ...

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putParcelable(LIST_STATE_ARG, list.onSaveInstanceState())
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        list.onRestoreInstanceState(savedInstanceState.getParcelable(LIST_STATE_ARG))
    }

}
Phosphide answered 15/6, 2020 at 23:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.