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 :)
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.
Try this: my_listview. setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } });
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.
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))
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With