我想知道如何创建类似于 instagram 的 backstack 的东西。
我有一个应用程序,它有一个底部导航栏,它打开 3 个不同的片段(、、、MapFragment)HostFragment,ProfileFragment在里面,当用户单击一个按钮时HostFragment,我创建了一个名为 的新片段:Host2Fragment
Tab1 Tab2 Tab3
[MapFragment][HostFragment][ProfileFragment]
.
.
.
[Host2Fragment]
一些例子:
注意:Tab1/MapFragment 是主片段
- 用户已开启
Host2Fragment,按返回可返回HostFragment- 再次按下返回到Tab1
- 用户在
Host2Fragment,点击Tab2回到HostFragment
本质上,按下返回,应该只是剥离所有层回到主片段(Tab1),并在这样做的同时更新底部导航栏。我还想保留片段的状态,这样当我点击返回它时,它应该仍然处于相同的状态
到目前为止我所拥有的:
主要活动
class MainActivity : AppCompatActivity(){
private val mapFragment: Fragment = MapFragment()
private val hostFragment: Fragment = HostFragment()
private val profileFragment: Fragment = ProfileFragment()
private val fm = supportFragmentManager
private var activeFragment = mapFragment
lateinit var toolbar: ActionBar
private val mOnNavigationItemSelectedListener =
BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_map -> {
fm.beginTransaction().hide(activeFragment).show(mapFragment).commit()
activeFragment = mapFragment
return@OnNavigationItemSelectedListener true
}
R.id.navigation_host -> {
fm.beginTransaction().hide(activeFragment).show(hostFragment).commit()
activeFragment = hostFragment
return@OnNavigationItemSelectedListener true
}
R.id.navigation_profile -> {
fm.beginTransaction().hide(activeFragment).show(profileFragment).commit()
activeFragment = profileFragment
return@OnNavigationItemSelectedListener true
}
}
false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fm.beginTransaction().add(R.id.container, profileFragment, "profileFragment").hide(profileFragment).commit()
fm.beginTransaction().add(R.id.container, hostFragment, "hostFragment").hide(hostFragment).commit()
fm.beginTransaction().add(R.id.container, mapFragment, "mapFragment").commit()
toolbar = supportActionBar!!
val bottomNavigation: BottomNavigationView = findViewById(R.id.navigationView)
bottomNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
//the home Fragment
bottomNavigation.selectedItemId = R.id.navigation_map
}
}
主机片段
class HostFragment : Fragment(){
companion object {
private const val TAG = "HostFragment"
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_host, container, false)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val button = view.findViewById(R.id.button) as Button
button.setOnClickListener{
Log.d(HostFragment.TAG, "Clicked Host button")
fragmentManager?.beginTransaction()?.add(R.id.container, Host2Fragment(), "host2Fragment")?.commit()
}
}
}