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

Time:09-17

I am new in Android Studio and programming in general and I am trying to make an application in which from an Activity, I call a Fragment(making a part of the information on the screen disappear with the View.GONE property and at the same time make it appear the FrameLayout that will contain my Fragment). The problem is that in doing so, inside the fragment I try to call, there is a button to close tath fragment and return to the previous activity, but when i click that button it returns me to the MainActivity, not the Activity i was previously to click the button, what could my error be? I am attaching code and a gif so that you can see what I am doing wrong, I would appreciate your help (by the way, English is not my mother language, so I offer my apologies if this explanation is not well written)

Gif with visual explanation:

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

My code in DatosPokemonActivity (note that the function in the button also have a call to PokeAPi, but i think thats not the problem)

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

        }
    }
}

My code in 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()

        }
    }
}

I think thats the best way to explain my problem, feel free to ask for more information if you want, thanks :D !!!

Edit: As requested, here is the .xml code for StatsFragment and DatosPokemonActivity

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

CodePudding user response:

The problem with your code is you have underused the power of fragments in your code . You should not make use of Activity for any purpose if you have fragments in it . In your DatosPokemonActivity xml, you should have only FrameLayout in it which helps you to launch your fragment . The rest of the Layout , you need to shift them to a new Fragment .

Relation between Activity and Fragment : An activity is a place where group of Fragment reside and inherits it's lifecycle .

Reason for your Problem : Since your DatosPokemonActivity has only one Fragment , so when you hide / backstack on the StatsFragment , since it does not have any fragment in its backstack it navigates to its previous Activity and hence you miss all the information that you have on the DatosPokemonActivity .

Solution : Create a new Fragment . Consider it as Information Fragment .Shift all the xml code except your FrameLayout from DatosPokemonActivity to Information Fragment along with the needed code . Now on launch of your DatosPokemonActivity, launch the Information Fragment . Now when clicked on stats Button replace the Information Fragment with StatsFragment and also do not forget to add InformationFragment to backStack . Now , in your close button onClickListener just use fragmentManager.popBackStack and get back to your Information Fragment

CodePudding user response:

In StatsFragment

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

try this.

if you didn't use Jetpack mb this:

activity.supportFragmentManager?.popBackStack()
  • Related