简体   繁体   English

向后按下时碎片会被破坏。 我希望它在后退时不会被破坏,这样我就可以保存片段的状态

[英]Fragments are getting destroyed when back pressed. I want it to be not destroy when back press so that I can save the states of fragments

I created an Activity and added 3 fragments into it.我创建了一个 Activity 并向其中添加了 3 个片段。 One is HomeFragment, second is ProductDetailFragment, and third is CartFragment.第一个是 HomeFragment,第二个是 ProductDetailFragment,第三个是 CartFragment。 I have added multiple quantities of a product from ProductDetailFragment and I want the quantity detail to be saved even if I am back to HomeFragment and again coming back to ProductDetailFragment.我已经从 ProductDetailFragment 添加了多个产品数量,并且我希望保存数量详细信息,即使我返回到 HomeFragment 并再次返回到 ProductDetailFragment。 But as soon as I press back to go to HomeFragment, ProductDetailFragment is destroyed and if coming again to ProductDetailFragment quantity values are all wiped out.但是,一旦我按回 go 到 HomeFragment,ProductDetailFragment 就会被销毁,如果再次回到 ProductDetailFragment,数量值就会全部消失。

I have tried onSaveInstanceState to store the state even if fragment is destroyed but not working in this case.我试过 onSaveInstanceState 来存储 state 即使片段被破坏但在这种情况下不起作用。 Lemme show you my code:让我告诉你我的代码:

ProductDetailFragment产品细节片段

lateinit var binding: FragmentProductDetailBinding
    var quantityValue = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Toast.makeText(activity,"onCreateCalled",Toast.LENGTH_SHORT).show()
        if(savedInstanceState == null) {
            quantityValue = 0
        } else {
            quantityValue = savedInstanceState.getInt("quantity",0)
        }

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
       /// return inflater.inflate(R.layout.fragment_product_detail, container, false)


        binding = FragmentProductDetailBinding.inflate(inflater,container,false)
        binding.productDetails1 = arguments?.getParcelable("product")
        var productDetail = binding.productDetails1

       // var priceAmount = binding.priceAmount.text.toString().toFloat()

        Log.d("PriceAmount", binding.priceAmount.text.toString())

       // Log.d("ProductTitle", binding.productDetails1.title)
                binding.addButton.setOnClickListener {
                // Log.d("ProductDetail",initialValue.toString())
                if (productDetail == null) return@setOnClickListener
                quantityValue = quantityValue + 1
                binding.totalPriceText.text = "Total price"
                binding.quantityText.text = quantityValue.toString()
                binding.priceAmount.text = (productDetail.price * quantityValue).toString()


                // Log.d("ProductDetail",priceAmount.toString())
            }
            binding.removeButton.setOnClickListener {
                if (quantityValue != 0) {
                    if (productDetail == null) return@setOnClickListener
                    quantityValue = quantityValue - 1
                    binding.quantityText.text = quantityValue.toString()
                    //   binding.priceAmount.text = (priceAmount*quantityValue).toString()
                    binding.priceAmount.text = (productDetail.price * quantityValue).toString()

                }
            }

            binding.addCartButton.setOnClickListener{
            val bundle = Bundle()
            bundle.putString("quantity_text", String.format("%d",quantityValue))
            val cartFragment = CartFragment()
                cartFragment.arguments = bundle


            val ft = fragmentManager?.beginTransaction()
            ft?.replace(R.id.flFragment,cartFragment)
            ft?.addToBackStack("")
            ft?.commit()
            // Create the transaction
            // Create the transaction
        }
        Toast.makeText(activity,"onCreateViewCalled",Toast.LENGTH_SHORT).show()

        return binding.root
    }

  override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("quantity", quantityValue)

    }

HomeFragment主页片段

class HomeFragment : Fragment() {

    lateinit var binding: FragmentHomeBinding
    private val viewModel: HomeFragmentViewModel by lazy {
        ViewModelProvider(this).get(HomeFragmentViewModel::class.java)

    }



    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = FragmentHomeBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.viewModel = viewModel
        binding.lifecycleOwner = viewLifecycleOwner

        val clickListener = object: ClickListener{
            override fun onClick(itemProduct: ProductDataModel) {
                val productDetailFragment = ProductDetailFragment().apply {
                    arguments = bundleOf(Pair("product",itemProduct))
                }
                val ft : FragmentTransaction = fragmentManager!!.beginTransaction()
                ft.replace(R.id.flFragment, productDetailFragment,"PRODUCT_DETAIL_FRAGMENT")
                ft.addToBackStack(null)
                ft.commit()
            }

        }

        viewModel.products.observe(viewLifecycleOwner){
            if (it.size>0){
                //Log.d("HomeFragment",it.get(0).title)
                //Log.d("HomeFragment", it.get(0).image)
                binding.productRecyclerView.adapter = ProductListAdapter(it,clickListener)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        (activity as AppCompatActivity?)!!.supportActionBar!!.hide()

    }

    override fun onStop() {
        super.onStop()
        (activity as AppCompatActivity?)!!.supportActionBar!!.show()
    }

    override fun onDestroy() {
        super.onDestroy()
        Toast.makeText(activity,"onDestroyHomeFrag",Toast.LENGTH_SHORT).show()
    }

}

MainActivity ( In which all fragments are there )

class MainActivity : AppCompatActivity() {
private val viewModel:MainViewModel by viewModels()
`enter code here`var productDetailFragment = ProductDetailFragment()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    installSplashScreen().apply {
        setKeepOnScreenCondition{
            viewModel.isLoading.value
        }

    }
    setContentView(R.layout.activity_main)
    val homeFragment = HomeFragment()

    //Starting the fragment transaction from SupportFragmentManager class
    val ft : FragmentTransaction = supportFragmentManager.beginTransaction()
    ft.add(R.id.flFragment, homeFragment,"HOME_FRAGMENT")
    ft.addToBackStack(null)
    ft.commit()

enter code here } } enter code here } }

You can use SharedViewModel since both fragments share same activity.您可以使用SharedViewModel ,因为两个片段共享相同的活动。 You can add data that you want to preserve and when you go to the detail page view model still has the data you want because it depends on activity' lifecycle.您可以添加要保留的数据,当您 go 到详细页面视图时 model 仍然有您想要的数据,因为它取决于活动的生命周期。

Offical doc: https://developer.android.com/topic/libraries/architecture/viewmodel#sharing官方文档: https://developer.android.com/topic/libraries/architecture/viewmodel#sharing

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

相关问题 当我按回来时导航片段的问题 - Problem with navigating fragments when i press on back 如何在后台事件中销毁 tablayout 片段? - How can I destroy the tablayout fragments at the back event? 当按下“后退”按钮时,在片段中停止AsyncTask - Stop AsyncTask in Fragments when Back Button is pressed 当我从活动中向后按下时,以及在底部导航栏中切换片段时,如何保留recyclerview滚动位置 - How can I retain recyclerview scroll position when i back pressed from activity to fragment and when switching fragments in bottom nav bar 在 Android 中使用片段时处理回按 - Handling back press when using fragments in Android 我正在使用Fragments,当我按下后退按钮时,应用真的崩溃了。 它随机发生 - I'm using Fragments and when I press the back button really fast the app crashes. It happens randomly 使用碎片时按下后退按钮时调用OnResume - Call OnResume when Back Button Pressed when using Fragments 返回按碎片 - Back Press on fragments 按下返回按钮时定时器未关闭。 按下按钮时强制关闭错误 - Timer not shutting down when back button is pressed. Forceclose error on button press 片段中按返回按钮时如何显示警告消息 - How to show warning message when back button is pressed in fragments
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM