如何使用popBackStack()返回Android应用程序中的上一个片段?

时间:2020-02-10 18:37:39

标签: android kotlin

我正在尝试从活动中返回上一个片段,但是我无法使用该功能。

这是我的活动课堂中的相关代码:

    fun previousSubCountryListButtonClicked(view: View) {

        val fragmentManager = supportFragmentManager
        fragmentManager.popBackStack(R.id.navigation_scotland, POP_BACK_STACK_INCLUSIVE)

    }

这是我的片段类:

package com.riverstonetech.gositeuk.ui.scotland

import android.content.Intent
import android.content.Intent.getIntent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ProgressBar
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.google.firebase.firestore.FirebaseFirestore
import com.riverstonetech.gositeuk.CountriesActivity
import com.riverstonetech.gositeuk.R
import com.riverstonetech.gositeuk.RegionActivity
import kotlinx.android.synthetic.main.fragment_scotland.*

class ScotlandFragment : Fragment() {

    // Access a Cloud Firestore instance
    val db = FirebaseFirestore.getInstance()
    lateinit var adapter : ArrayAdapter<String>

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {


        val root = inflater.inflate(R.layout.fragment_scotland, container, false)

        (requireActivity() as CountriesActivity).initializeCustomActionBar(R.drawable.scotland_flag, R.string.title_regions)

        var regions : ArrayList<String>

        val docRef = db.collection("UKSites").document("Scotland")

        val progressBar: ProgressBar = root.findViewById(R.id.regionsLoadingProgressBar)

        docRef.get()
            .addOnSuccessListener { document ->

                progressBar?.visibility = ProgressBar.VISIBLE

                if (document != null) {

                    regions = document.get("Regions") as ArrayList<String>

                    adapter = ArrayAdapter(requireContext(), R.layout.list_item, regions)

                    regionsListView.adapter = adapter

                    regionsListView.setOnItemClickListener { parent, view, position, id ->

                        val intent = Intent(activity!!, RegionActivity::class.java)
                        intent.putExtra("SUB_COUNTRY", regions[position])
                        startActivity(intent)


                    }

                    progressBar?.visibility = ProgressBar.GONE

                } else {
                    Log.d("Debug", "No such document")
                }
            }
            .addOnFailureListener { exception ->
                Log.d("Debug", "get failed with ", exception)
            }

        return root
    }
}

我正在努力理解Android上的官方文档,因此,我将不胜感激。我需要在片段类中添加交易吗?

1 个答案:

答案 0 :(得分:0)

我使用finish()而不是编写代码来操作片段管理器。