简体   繁体   English

如何防止在底部导航视图中重新创建片段?

[英]How to prevent Fragment recreation in Bottom Navigation View?

I have successfully implemented Bottom Navigation View but whenever the navigate from one fragment to another the first fragment gets completely destroyed even when i'm on the same fragment and press the menu button for it it gets destroyed我已经成功实现了底部导航视图,但是每当从一个片段导航到另一个片段时,第一个片段就会被完全破坏,即使我在同一个片段上并按下菜单按钮它也会被破坏

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.ncapdevi.fragnav.FragNavController
import com.shivam.spaced.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity(), FragNavController.RootFragmentListener {

private lateinit var binding: ActivityMainBinding
private var selectedFragment: Fragment? = null



override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = DataBindingUtil.setContentView(this, R.layout.activity_main)


    binding.bottomNavigation.setOnNavigationItemSelectedListener { menuItem ->
        when (menuItem.itemId) {
            R.id.home_item -> {
                selectedFragment = HomeFragment()
            }
            R.id.notification_item -> {
                selectedFragment = NotificationsFragment()
            }
            R.id.camera_item -> {
                selectedFragment = CameraFragment()
            }
            R.id.settings_item -> {
                selectedFragment = SettingsFragment()
            }
        }

        selectedFragment.id
        if (selectedFragment != null) {
            supportFragmentManager.beginTransaction()
                .replace(R.id.fragment_container, selectedFragment!!).commit()
        }

        return@setOnNavigationItemSelectedListener true
    }
}

} }

supportFragmentManager
.beginTransaction()
.add(R.id.fragment_container, selectedFragment!!)
.commit()

Transition.add function adds a fragment to a container and Transition.replace function removes the current container's fragment and add a new to it. Transition.add function 将片段添加到容器中, Transition.replace function 删除当前容器的片段并添加新片段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM