Skip to content

Commit 83908d6

Browse files
1951FDGhannesa2
authored andcommitted
RecyclerView: Set stateRestorationPolicy
PREVENT_WHEN_EMPTY (restore last scroll position when activity is recreated, tested with dev option, don't keep activities)
1 parent 926a524 commit 83908d6

1 file changed

Lines changed: 13 additions & 7 deletions

File tree

LogcatCoreLib/src/main/java/info/hannes/logcat/base/LogBaseFragment.kt

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,12 +51,15 @@ abstract class LogBaseFragment : Fragment() {
5151
it.recycledViewPool.setMaxRecycledViews(R.layout.item_log, DEFAULT_MAX_SCRAP)
5252
}
5353
// empty adapter to avoid "E/RecyclerView﹕ No adapter attached; skipping layou..."
54-
logListAdapter = LogListAdapter(mutableListOf(), currentFilter)
54+
logListAdapter = LogListAdapter(mutableListOf(), currentFilter).also {
55+
it.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
56+
}
57+
5558
logsRecycler.adapter = logListAdapter
5659

5760
setFilter2LogAdapter("")
5861

59-
showLogContent()
62+
showLogContent(savedInstanceState)
6063

6164
setHasOptionsMenu(true)
6265

@@ -71,16 +74,19 @@ abstract class LogBaseFragment : Fragment() {
7174
return view
7275
}
7376

74-
private fun showLogContent() {
77+
private fun showLogContent(savedInstanceState: Bundle?) {
7578
lifecycle.coroutineScope.launch(Dispatchers.Main) {
7679
val logEntries = withContext(Dispatchers.Default) {
7780
readLogFile()
7881
}
7982
logListAdapter?.setItems(logEntries)
80-
logListAdapter?.itemCount?.minus(1)?.let { logsRecycler.scrollToPosition(it) }
83+
84+
if (savedInstanceState == null) {
85+
logListAdapter?.itemCount?.minus(1)?.let { logsRecycler.scrollToPosition(it) }
86+
}
8187

8288
if (live) {
83-
Handler(Looper.getMainLooper()).postDelayed({ showLogContent() }, 1000)
89+
Handler(Looper.getMainLooper()).postDelayed({ showLogContent(null) }, 1000)
8490
}
8591
}
8692
}
@@ -140,7 +146,7 @@ abstract class LogBaseFragment : Fragment() {
140146
switch.setOnCheckedChangeListener { _, isChecked ->
141147
live = isChecked
142148
if (live)
143-
showLogContent()
149+
showLogContent(null)
144150
}
145151
super.onCreateOptionsMenu(menu, inflater)
146152
}
@@ -169,7 +175,7 @@ abstract class LogBaseFragment : Fragment() {
169175
}
170176
R.id.menu_clear -> {
171177
clearLog()
172-
showLogContent()
178+
showLogContent(null)
173179
}
174180
R.id.menu_show_verbose -> {
175181
item.isChecked = true

0 commit comments

Comments
 (0)