如何从同一片段中的关闭按钮关闭片段?

How can i close a Fragment, from a close button in the same fragment?

我是 Android Studio 和一般编程的新手,我正在尝试制作一个应用程序,其中来自 Activity,我调用一个片段(制作关于屏幕随着 View.GONE 属性 消失,同时使它出现将包含我的 Fragment 的 FrameLayout)。问题是在这样做的过程中,在我尝试调用的片段中,有一个按钮可以关闭 tath 片段和 return 到前一个 activity,但是当我单击该按钮时它 return 将我转到 MainActivity,而不是我之前单击按钮的 Activity,我的错误可能是什么?我附上代码和 gif 以便您可以看到我做错了什么,非常感谢您的帮助(顺便说一下,英语不是我的母语,所以如果这个解释写得不好,我深表歉意)

带有视觉解释的 Gif:

https://s9.gifyu.com/images/gif_explanation.gif

我在 DatosPokemon 中的代码Activity(注意按钮中的函数也调用了 PokeAPI,但我认为这不是问题所在)

package com.example.pokedexv4

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.example.pokedexv4.APIConexion.Retrofit
import com.example.pokedexv4.databinding.ActivityDatosPokemonBinding
import com.example.pokedexv4.datosdeAPI.Ability
import com.example.pokedexv4.datosdeAPI.PokemonEsqueleto
import com.example.pokedexv4.datosdeAPI2.FlavorTextEntry
import com.example.pokedexv4.datosdeAPI2.PokemonDescripcion
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_datos_pokemon.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.lang.NullPointerException

class DatosPokemonActivity : AppCompatActivity() {

    private lateinit var binding: ActivityDatosPokemonBinding
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDatosPokemonBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportActionBar?.hide()

        datospkm()
        normalOshiny()
        visualizador()
        pidePermiso()
        cambioStatFragment(posicion)

    }

 fun cambioStatFragment(position: String) {

        val statsFragment = StatsFragment()

        binding.STATS.setOnClickListener {

            pantallaDatos.visibility = View.GONE
            frameFragments.isVisible = true

            CoroutineScope(Dispatchers.IO).launch {

                val respuesta =
                    Retrofit.getRetrofit.pokemonesPokedex("$position") //position en la lista

                if (respuesta.isSuccessful) {

                    runOnUiThread {

                        val estadisticas = respuesta.body()!!

                        val hp = estadisticas.stats[0].base_stat
                        val atk = estadisticas.stats[1].base_stat
                        val def = estadisticas.stats[2].base_stat
                        val spatk = estadisticas.stats[3].base_stat
                        val spdef = estadisticas.stats[4].base_stat
                        val spd = estadisticas.stats[5].base_stat

                        var datos: Bundle = Bundle()
                        datos.putString("pasarhp", hp.toString())
                        datos.putString("pasaratk", atk.toString())
                        datos.putString("pasardef", def.toString())
                        datos.putString("pasarspatk", spatk.toString())
                        datos.putString("pasarspdef", spdef.toString())
                        datos.putString("pasarspd", spd.toString())
                        statsFragment.arguments = datos
                    }

                    supportFragmentManager.beginTransaction().apply {
                        replace(R.id.frameFragments, statsFragment)
                        addToBackStack("grafico") //<--?
                        commit()
                    }
                }
            }

        }
    }
}

我在 StatsFragment 中的代码

package com.example.pokedexv4

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import com.example.pokedexv4.databinding.FragmentStatsBinding
import com.github.mikephil.charting.data.RadarData
import com.github.mikephil.charting.data.RadarDataSet
import com.github.mikephil.charting.data.RadarEntry
import com.github.mikephil.charting.interfaces.datasets.IRadarDataSet
import kotlinx.android.synthetic.main.activity_datos_pokemon.*

class StatsFragment : Fragment(R.layout.fragment_stats) {

    private var _binding: FragmentStatsBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentStatsBinding.inflate(inflater, container, false)

        cerrarGrafico()

        return binding.root
    }


    fun cerrarGrafico() {

        binding.btnCerrar.setOnClickListener {
            frameFragments!!.visibility = View.GONE
            pantallaDatos.isVisible = true

            val activity = view?.context as AppCompatActivity
            activity.supportFragmentManager?.beginTransaction()?.hide(this)?.commit()

        }
    }
}

我认为这是解释我的问题的最佳方式,如果需要,请随时询问更多信息,谢谢 :D !!!

编辑:根据要求,这是 StatsFragment 和 DatosPokemonActivity

的 .xml 代码

.xml 达托斯口袋妖怪Activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/fondoinfopkmynavegador"
    tools:context=".DatosPokemonActivity"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/frameFragments"
        android:layout_width="match_parent"
        android:layout_height="345dp"
        android:layout_marginTop="143.4dp"
        android:layout_marginStart="40.8dp"
        android:layout_marginEnd="40.8dp"
        android:layout_marginBottom="18dp"
        android:visibility="gone">

    </FrameLayout>

    <LinearLayout
        android:id="@+id/pantallaDatos"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="42dp"
        android:layout_marginTop="145dp"
        android:layout_marginEnd="42dp"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="326dp"
            android:layout_height="245dp"
            android:orientation="horizontal">

            <LinearLayout
                android:layout_width="210dp"
                android:layout_height="245dp"
                android:orientation="vertical">

                <LinearLayout
                    android:layout_width="210dp"
                    android:layout_height="193dp"
                    android:orientation="horizontal">

                    <ImageView
                        android:id="@+id/imgpkm"
                        android:layout_width="180dp"
                        android:layout_height="180dp"
                        android:contentDescription="@string/contentDescrip"
                        tools:src="@mipmap/pkm001" />

                    <ImageView
                        android:id="@+id/imgpkmshiny"
                        android:layout_width="180dp"
                        android:layout_height="180dp"
                        android:contentDescription="@string/contentDescrip"
                        android:visibility="gone"
                        tools:src="@mipmap/pkm002" />

                    <LinearLayout
                        android:layout_width="30dp"
                        android:layout_height="200dp"
                        android:orientation="vertical">

                        <ImageButton
                            android:id="@+id/btnNormalVersion"
                            android:layout_width="30dp"
                            android:layout_height="25dp"
                            android:layout_marginTop="5dp"
                            android:background="@null"
                            android:contentDescription="@string/contentDescrip"
                            android:scaleType="fitCenter"
                            android:src="@drawable/normalpokemon"
                            tools:ignore="TouchTargetSizeCheck,ImageContrastCheck,SpeakableTextPresentCheck,DuplicateSpeakableTextCheck" />

                        <ImageButton
                            android:id="@+id/btnShinyVersion"
                            android:layout_width="30dp"
                            android:layout_height="25dp"
                            android:layout_marginTop="135dp"
                            android:background="@null"
                            android:contentDescription="@string/contentDescrip"
                            android:scaleType="fitCenter"
                            android:src="@drawable/destelloshiny"
                            tools:ignore="TouchTargetSizeCheck,SpeakableTextPresentCheck,ImageContrastCheck" />
                    </LinearLayout>

                </LinearLayout>

                <LinearLayout
                    android:layout_width="212dp"
                    android:layout_height="match_parent"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="35dp"
                        android:layout_height="match_parent"
                        android:orientation="vertical">

                        <ImageView
                            android:layout_width="20dp"
                            android:layout_height="20dp"
                            android:layout_marginStart="8dp"
                            android:layout_marginTop="8dp"
                            android:contentDescription="@string/contentDescrip"
                            android:src="@drawable/ic_baseline_height_24" />

                        <ImageView
                            android:layout_width="20dp"
                            android:layout_height="20dp"
                            android:layout_marginStart="8dp"
                            android:layout_marginTop="2dp"
                            android:contentDescription="@string/contentDescrip"
                            android:src="@drawable/peso" />

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="43dp"
                        android:layout_height="match_parent"
                        android:orientation="vertical">

                        <TextView
                            android:id="@+id/altura"
                            android:layout_width="43dp"
                            android:layout_height="22dp"
                            android:layout_marginTop="3dp"
                            android:gravity="end"
                            android:textSize="20sp"
                            android:textStyle="bold"
                            tools:text="0.7" />

                        <TextView
                            android:id="@+id/peso"
                            android:layout_width="43dp"
                            android:layout_height="27dp"
                            android:layout_marginTop="1dp"
                            android:gravity="end"
                            android:textSize="20sp"
                            android:textStyle="bold"
                            tools:text="0.5" />

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="30dp"
                        android:layout_height="match_parent"
                        android:orientation="vertical">

                        <TextView
                            android:id="@+id/metros"
                            android:layout_width="wrap_content"
                            android:layout_height="22dp"
                            android:layout_marginStart="5dp"
                            android:layout_marginTop="3dp"
                            android:text="@string/metros"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/kilo"
                            android:layout_width="wrap_content"
                            android:layout_height="27dp"
                            android:layout_marginStart="5dp"
                            android:layout_marginTop="1dp"
                            android:text="@string/kilos"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_marginTop="1dp"
                        android:orientation="horizontal">

                        <ImageView
                            android:id="@+id/tipodato"
                            android:layout_width="40dp"
                            android:layout_height="40dp"
                            android:layout_marginStart="10dp"
                            android:layout_marginTop="10dp"
                            android:contentDescription="@string/contentDescrip"
                            tools:src="@mipmap/tipoplanta" />

                        <ImageView
                            android:id="@+id/tipo2dato"
                            android:layout_width="40dp"
                            android:layout_height="40dp"
                            android:layout_marginStart="8dp"
                            android:layout_marginTop="10dp"
                            android:contentDescription="@string/contentDescrip"
                            tools:src="@mipmap/tipoveneno" />

                    </LinearLayout>

                </LinearLayout>

            </LinearLayout>
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:layout_marginTop="2dp"
                    android:text="@string/nombre"
                    android:textSize="15sp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/nombredato"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:gravity="end"
                    android:paddingEnd="5dp"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    tools:text="Bulbasaur" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:layout_marginTop="7dp"
                    android:paddingEnd="5dp"
                    android:text="@string/hab"
                    android:textSize="15sp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/habilidad"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:autoSizeTextType="uniform"
                    android:gravity="end"
                    android:paddingEnd="5dp"
                    android:textSize="17sp"
                    android:textStyle="bold"
                    tools:text="Espesura" />

                <TextView
                    android:id="@+id/habilidad2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:autoSizeTextType="uniform"
                    android:gravity="end"
                    android:paddingEnd="5dp"
                    android:textSize="17sp"
                    android:textStyle="bold"
                    tools:text="Espesura" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:paddingEnd="5dp"
                    android:text="@string/haboculta"
                    android:textSize="15sp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/habilidadoculta"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:gravity="end"
                    android:paddingEnd="5dp"
                    android:textSize="17sp"
                    android:textStyle="bold"
                    tools:text="Clorofila" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:layout_marginTop="7dp"
                    android:paddingEnd="5dp"
                    android:text="@string/gruphuevo"
                    android:textSize="15sp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/grupohuevo1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:gravity="end"
                    android:paddingEnd="5dp"
                    android:textSize="16sp"
                    android:textStyle="bold"
                    tools:text="Monstruo" />

                <TextView
                    android:id="@+id/grupohuevo2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:gravity="end"
                    android:paddingEnd="5dp"
                    android:textSize="16sp"
                    android:textStyle="bold"
                    tools:text="Planta" />
            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_width="326dp"
            android:layout_height="115dp"
            android:orientation="vertical">

            <TextView
                android:id="@+id/descripcion"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="5dp"
                android:textAlignment="center"
                android:textSize="17sp"
                android:textStyle="bold"
                tools:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Otro texto de relleno que pueda ocupar... " />

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
      android:layout_width="327dp"
      android:layout_height="120dp"
      android:orientation="horizontal"
      android:layout_marginTop="5dp"
      android:layout_marginStart="40dp"
      android:layout_marginEnd="50dp">

      <LinearLayout
          android:layout_width="125dp"
          android:layout_height="wrap_content"
          android:orientation="vertical">

          <Button
              android:id="@+id/STATS"
              android:layout_width="115dp"
              android:layout_height="50dp"
              android:text="@string/stats"
              android:textSize="16sp"
              android:layout_marginTop="11dp"
              tools:ignore="TouchTargetSizeCheck" />

          <Button
              android:id="@+id/MOVES"
              android:layout_width="115dp"
              android:layout_height="50dp"
              android:backgroundTint="#FDD835"
              android:text="@string/moves"
              android:textColor="@color/black"
              android:textSize="16sp"
              tools:ignore="TextContrastCheck,TouchTargetSizeCheck" />


      </LinearLayout>

      <ImageButton
          android:id="@+id/vozPokemon"
          android:layout_width="70dp"
          android:layout_height="70dp"
          android:layout_marginTop="25dp"
          android:layout_marginStart="5dp"
          android:layout_marginEnd="35dp"
          android:layout_marginBottom="10dp"
          android:background="@null"
          android:contentDescription="@string/contentDescrip"
          android:scaleType="fitXY"
          android:src="@mipmap/botonaudio"
          tools:ignore="SpeakableTextPresentCheck,DuplicateSpeakableTextCheck" />

      <com.gauravk.audiovisualizer.visualizer.WaveVisualizer
          xmlns:custom="http://schemas.android.com/apk/res-auto"
          android:id="@+id/wave"
          android:layout_width="72dp"
          android:layout_height="55dp"
          android:layout_marginTop="34dp"
          android:layout_marginEnd="30dp"
          custom:avDensity="0.07"
          custom:avType="outline"
          custom:avColor="#FDD835"
          custom:avSpeed="fast"
          custom:avWidth="2dp"
          custom:avGravity="bottom"
          tools:ignore="MissingClass" />

  </LinearLayout>

</LinearLayout>

.xml 对于 StatsFragment

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".StatsFragment">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="260dp"
            android:layout_height="50dp"
            android:layout_marginStart="20dp"
            android:text="@string/tituloestadisticas"
            android:textAlignment="textStart"
            android:textSize="30sp"
            android:textStyle="italic|bold"
            android:background="@color/white" />

        <ImageButton
            android:id="@+id/btnCerrar"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@null"
            android:contentDescription="@string/contentDescrip"
            android:src="@drawable/ic_baseline_close_24"
            tools:ignore="DuplicateSpeakableTextCheck,ImageContrastCheck" />

    </LinearLayout>


    <LinearLayout
        android:layout_width="330dp"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:orientation="horizontal"
        android:paddingTop="4dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingStart="23dp"
>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/ATK"
                android:textAlignment="center"
                android:textSize="15sp"
                android:layout_marginTop="70dp"
                android:textStyle="bold|italic" />

            <TextView
                android:id="@+id/STAT_ATK"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center"
                android:textSize="15sp"
                android:textStyle="bold|italic"
                tools:text="@string/ATK" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="75dp"
                android:text="@string/DEF"
                android:textAlignment="center"
                android:textSize="15sp"
                android:textStyle="bold|italic" />

            <TextView
                android:id="@+id/STAT_DEF"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/DEF"
                android:textAlignment="center"
                android:textSize="15sp"
                android:textStyle="bold|italic" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/HP"
                android:textAlignment="center"
                android:textSize="15sp"
                android:textStyle="bold|italic" />

            <TextView
                android:id="@+id/STAT_HP"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center"
                android:textSize="15sp"
                android:textStyle="bold|italic"
                android:text="@string/HP" />

            <com.github.mikephil.charting.charts.RadarChart
                android:id="@+id/graficoRadar"
                android:layout_width="206dp"
                android:layout_height="215dp"
                android:background="@color/white"
                android:backgroundTint="@color/white" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/SPD"
                android:textAlignment="center"
                android:textSize="15sp"
                android:textStyle="bold|italic" />

            <TextView
                android:id="@+id/STAT_SPD"
                android:layout_width="match_parent"
                android:layout_height="47dp"
                android:text="@string/SPD"
                android:textAlignment="center"
                android:textSize="15sp"
                android:textStyle="bold|italic" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingEnd="20dp">


            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/SP_ATK"
                android:layout_marginTop="70dp"
                android:textSize="15sp"
                android:textStyle="bold|italic" />

            <TextView
                android:id="@+id/STAT_SPATK"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/SP_ATK"
                android:textSize="15sp"
                android:textStyle="bold|italic" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="75dp"
                android:text="@string/SP_DEF"
                android:textSize="15sp"
                android:textStyle="bold|italic" />

            <TextView
                android:id="@+id/STAT_SPDEF"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="15sp"
                android:textStyle="bold|italic"
                android:text="@string/SP_DEF" />

        </LinearLayout>


    </LinearLayout>


</LinearLayout>

在 StatsFragment 中

binding.btnCerrar.setOnClickListener {
...
activity.supportFragmentManager?.beginTransaction()?.hide(this)?.commit() // replace this with :
     findNavController().navigateUp()
}

试试这个。

如果你没有使用 Jetpack mb 这个:

activity.supportFragmentManager?.popBackStack()

您的代码存在的问题是您没有充分利用代码中片段的力量。如果其中有片段,则不应出于任何目的使用 Activity。在你的 DatosPokemonActivity xml 中,你应该只有 FrameLayout 可以帮助你启动你的片段。 Layout 的其余部分,您需要将它们转移到新的 Fragment 中。

Activity 和 Fragment 之间的关系: activity 是一组 Fragment 所在的地方,并继承它的生命周期。

您遇到问题的原因: 由于您的 DatosPokemonActivity 只有一个 Fragment ,因此当您在 StatsFragment 上隐藏/回溯堆栈时,由于它的回溯堆栈中没有任何片段,因此它会导航到其先前的 Activity ,因此您会错过所有信息你在 DatosPokemonActivity .

解决方案: 创建一个新的片段。将其视为信息片段。将除 FrameLayout 之外的所有 xml 代码与所需代码一起从 DatosPokemonActivity 转移到信息片段。现在启动您的 DatosPokemonActivity,启动 Information Fragment 。现在,当单击统计按钮时,将 Information Fragment 替换为 StatsFragment 并且不要忘记将 InformationFragment 添加到 backStack 。现在,在您的关闭按钮 onClickListener 中只需使用 fragmentManager.popBackStack 并返回您的信息片段