I have created a notes app in which files are stored in internal storage. I have many fragments associated with a single activity. The first fragment has a ListView that shows all the saved files. On clicking on any item of ListView, a new fragment opens that shows the file's data. The app also has a Toolbar with navigation drawer. On pressing the back button of Toolbar from the second fragment, the ListView's scroll position remains the same. However, on clicking the back button (of the OS), the ListView scrolls back to the first item. I am also using the Navigation library to go from one fragment to another.
Here is my Fragment's code containing ListView:
CustomArrayAdapter arrayAdapter;
ArrayList<String> FilesInFolder;
FilesInFolder = GetFiles(getActivity().getFilesDir());
arrayAdapter = new CustomArrayAdapter(FilesInFolder, getContext());
Collections.sort(FilesInFolder);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String title = String.valueOf(parent.getItemAtPosition(position));
Bundle bundle = new Bundle();
bundle.putString("fileName", title);
Navigation.findNavController(getView()).navigate(R.id.action_nav_home_to_nav_view_note, bundle);
}
});
Here is my second fragment's back press code:
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
OnBackPressedCallback callback = new OnBackPressedCallback(
true // default to enabled
) {
@Override
public void handleOnBackPressed() {
Navigation.findNavController(getView()).navigate(R.id.action_nav_view_note_to_nav_home);
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(
this, // LifecycleOwner
callback);
}
The CustomArrayAdapter only sets text to each item in ListView and an image next to it.
Now, how can I save or maintain the ListView's scroll position even after going to another fragment and returning again on back press?