This repository has been archived by the owner on Oct 15, 2020. It is now read-only.
/
FrameActivity.kt
105 lines (89 loc) · 3.06 KB
/
FrameActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package com.lockwood.pagerdemo
import android.os.Bundle
import android.view.MenuItem
import androidx.fragment.app.Fragment
import com.lockwood.pagerdemo.fragment.MessageFragment
class FrameActivity : BaseNavigationActivity(R.layout.activity_frame) {
private var selectedItem: Int = HOME_NAVIGATION_ITEM
private val currentFragment: Fragment?
get() = supportFragmentManager.findFragmentById(R.id.container)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
showMessageFragment(HOME_NAVIGATION_ITEM)
}
}
override fun onBackPressed() = with(navigationHistory) {
if (!isEmpty()) {
selectBottomNavigationItem(popLastSelected())
} else {
handleBackStackFragments()
}
}
private fun handleBackStackFragments() {
val tag = currentFragment?.tag
val backStuckIsEmpty = supportFragmentManager.backStackEntryCount == 1
val isStartFragment = tag == 0.toString()
if (backStuckIsEmpty && isStartFragment) {
finish()
} else {
val fragmentPopped = supportFragmentManager.popBackStackImmediate(tag, 0)
if (fragmentPopped) {
checkBottomNavigationItem(tag?.toIntOrNull() ?: HOME_NAVIGATION_ITEM)
} else {
selectBottomNavigationItem(HOME_NAVIGATION_ITEM)
}
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean = with(item) {
return selectNavigationItem(order)
}
private fun checkBottomNavigationItem(id: Int) {
navigation.menu.getItem(id).isChecked = true
selectedItem = id
}
private fun selectBottomNavigationItem(id: Int) {
selectNavigationItem(id, false)
checkBottomNavigationItem(id)
}
private fun selectNavigationItem(id: Int, isPush: Boolean = true): Boolean {
return if (id == selectedItem) {
// do nothing if already selected
false
} else {
// update selected tem
selectedItem = id
if (isPush) {
navigationHistory.pushItem(id)
}
when (id) {
in HOME_NAVIGATION_ITEM..navigation.menu.size() -> {
showMessageFragment(id)
true
}
else -> {
false
}
}
}
}
private fun showMessageFragment(id: Int) {
val fragment = MessageFragment.newInstance(id)
val tag = id.toString()
replaceFragment(fragment, tag)
}
private fun replaceFragment(
fragment: Fragment,
tag: String
) {
val fragmentPopped = supportFragmentManager.popBackStackImmediate(tag, 0)
if (!fragmentPopped) {
supportFragmentManager.beginTransaction().apply {
replace(R.id.container, fragment, tag)
addToBackStack(tag)
}.commit()
}
}
companion object {
}
}