我怎么能关闭一个片段,从一个关闭按钮在同一片段?



我是Android Studio和编程的新手,我正试图从一个活动中创建一个应用程序,我称之为片段(使屏幕上的信息的一部分随着视图消失)。GONE属性,同时使它出现的框架布局,将包含我的片段)。问题是,在这样做的时候,在片段我试图调用,有一个按钮来关闭碎片,并返回到上一个活动,但当我点击该按钮,它返回我到MainActivity,而不是活动我以前点击按钮,我的错误是什么?我附上代码和一个gif,这样你就可以看到我做错了什么,我很感激你的帮助(顺便说一句,英语不是我的母语,所以如果这个解释写得不好,我表示歉意)

Gif with visual explanation:

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

我的代码在DatosPokemonActivity(注意,在按钮的功能也有一个调用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 DatosPokemonActivity

<?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 for 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>

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

活动与片段的关系:活动是片段组驻留的地方,并继承它的生命周期。

问题原因:因为你的DatosPokemonActivity只有一个片段,所以当你在StatsFragment上隐藏/backstack时,因为它没有任何片段在它的backstack中,它导航到它以前的Activity,因此你错过了你在DatosPokemonActivity上的所有信息。

解决方案:创建一个新的Fragment。将它视为信息片段。将除了framayout之外的所有xml代码从DatosPokemonActivity转移到信息片段以及所需的代码。现在在启动DatosPokemonActivity时,启动Information Fragment。现在当点击stats按钮时,用StatsFragment替换InformationFragment,也不要忘记将InformationFragment添加到backStack。现在,在你的关闭按钮onClickListener只使用fragmentManager。popBackStack和get back to your Information Fragment

In StatsFragment

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

试试这个。

如果你没有使用Jetpack,请点击此处:

activity.supportFragmentManager?.popBackStack()

最新更新