Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last ListView state when coming back from Activity

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 :)

like image 391
Haider Abbas Avatar asked Jun 15 '20 22:06

Haider Abbas


People also ask

How to Save state of ListView in android?

Since the MainActivity goes to onPause() -> onStop() method when the user clicked a list item, I am saving the state of ListView inside onPause(). For get the return Parcelable value I use a global variable called state.

How to get data from ListView by Clicking item on ListView?

Try this: my_listview. setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } });


2 Answers

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.

like image 154
iknow Avatar answered Oct 19 '22 09:10

iknow


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))
    }

}
like image 45
chef417 Avatar answered Oct 19 '22 09:10

chef417