简体   繁体   English

在 Android 应用中的活动之间切换后,如何切换回之前的片段?

[英]How do I switch back to a previous fragment after switching between activities in my Android app?

I have one custom fragment, Fragment A and two custom activities, Activity A and Activity B. I have a button on each of them in the top left hand corner which when clicked should go back to the previous fragment or activity.我有一个自定义片段 Fragment A 和两个自定义活动 Activity A 和 Activity B。我在每个片段的左上角都有一个按钮,单击该按钮时应返回到前一个片段或活动。 I switch from Fragment A to Activity A using an intent(...) call and the same thing when switching from Activity A to Activity B. I switch from Activity B to Activity A with an intent(...) call but I cannot switch from Activity A to fragment A using an intent(...) call.我使用intent(...)调用从 Fragment A 切换到 Activity A,从 Activity A 切换到 Activity B 时也是如此。我使用intent(...)调用从 Activity B 切换到 Activity A,但我不能使用intent(...)调用从活动 A 切换到片段 A。 I have tried using finish() in Activity A to get back to Fragment A but it sometimes results in Activity B being displayed if I have previously visited it before trying to switch to Fragment A. Any help in solving this conundrum would be greatly appreciated.我曾尝试在 Activity A 中使用finish()返回到 Fragment A,但如果我之前在尝试切换到 Fragment A 之前访问过它,有时会导致显示 Activity B。对于解决这个难题的任何帮助将不胜感激。

Here is the code for Fragment A:这是片段A的代码:

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 com.riverstonetech.gositeuk.returnToFragment
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 fragmentTransaction = returnToFragment.fragmentManager.beginTransaction()
        fragmentTransaction.add(R.id.navigation_scotland, this)
        fragmentTransaction.addToBackStack("ScotlandFragment")
        fragmentTransaction.commit()

        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
    }
}

Here is the relevant code for Activity A:这是活动A的相关代码:

    fun previousSubCountryListButtonClicked(view: View) {

        if ( returnToFragment.fragmentManager.backStackEntryCount > 0) {

            returnToFragment.fragmentManager.popBackStack()

        }

    }

Here is the relevant code for my Activity B:这是我的活动 B 的相关代码:

    fun listPreviousSitesClicked(view: View) {

        var intent: Intent

        when (previousActivityName) {

            "CountyActivity" -> {
                intent = Intent(this, CountyActivity::class.java)
                intent.putExtra("SUB_COUNTRY", subCountry)
                startActivity(intent)
            }
            "RegionActivity" -> {
                intent = Intent(this, RegionActivity::class.java)
                intent.putExtra("SUB_COUNTRY", subCountry)
                startActivity(intent)
            }

            else -> Log.i("INFO", "Unknown activity")

        }


    }

Here is the code for my object returnToFragment这是我的对象returnToFragment的代码

package com.riverstonetech.gositeuk

import androidx.fragment.app.FragmentActivity

object returnToFragment: FragmentActivity() {

    var fragmentManager = supportFragmentManager

}

You are switching from Fragment A to Activity A using the intent function.您正在使用意图函数从Fragment A切换到Activity A

you are doing the same thing when moving forward from Activity A to Activity B .Activity A前进到Activity B时,您正在做同样的事情。

When you are going back, finish Activity B then finish Activity A .当你回去时,完成Activity B然后完成Activity A Fragment A will then be visible to the user.然后Fragment A将对用户可见。

Don't go back by calling the intent method, just use finish.不要通过调用intent方法返回,只需使用finish。

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

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