1

I have viewpager tab fragment and from one tabb fragment on button click it open another fragment and another second fragment i want to add event of backpress as i am doing backpress it exiting application as i have written code of Double back press exit code in my root fragment and i dont want this code to call in my another second fragment as i want simply one step back to my previous fragment As here is the code

 R.id.Recharge -> {

            val pl = Payment_History()

            fragmentTransaction = fragmentManager!!.beginTransaction()
            fragmentTransaction.replace(R.id.frame_container, paypal)
            fragmentTransaction.addToBackStack(null)
            fragmentTransaction.commit()


        }

In Payment history i am calling on Back press override function

override fun onBackPressed(): Boolean {
    super.onBackPressed()
}

and on clicking on Paymenthistory it called exit code from application. i want that it back to previous fragment. As I have written this fragment code but not working. Any one have idea how to back second nested fragment to previous fragment.

My OnBackPress code in my MainActivity

    override fun onBackPressed() {
    // TODO Auto-generated method stub
    try {
    if (getFragmentManager().getBackStackEntryCount() == 0) {

        if (doubleBackToExitPressedOnce) {

            //super.onBackPressed();
            val startMain = Intent(Intent.ACTION_MAIN)
            startMain.addCategory(Intent.CATEGORY_HOME)
            startMain.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            pref!!.setLoggedIn(true)
            startMain.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK
            startMain.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
            startActivity(startMain)
            return
        }

        this.doubleBackToExitPressedOnce = true
        Toast.makeText(this, "Please click again to exit", Toast.LENGTH_SHORT).show()

        Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000)
    }

        }catch (e:Exception){
        println("homemessage"+ e.message)
    }
}
Jyoti
  • 87
  • 3
  • 12

5 Answers5

0

Add your fragment to backstack and then in your onBackPressed method do something like this:

@Override 
public void onBackPressed() { 
    if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
        getSupportFragmentManager().popBackStack(); 
    } else { 
        this.finish(); 
    }
}

For more information see this

Hope this is what you are looking for and it helps you.

AndiM
  • 2,196
  • 2
  • 21
  • 38
0

Try this (Instead of "replace" use "add")

fragmentTransaction = fragmentManager!!.beginTransaction()
fragmentTransaction.add(R.id.frame_container, paypal)
fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()

and

@Override 
public void onBackPressed() { 
    if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
        getSupportFragmentManager().popBackStack(); 
    } else { 
        this.finish(); 
    }
}
J Ramesh
  • 548
  • 4
  • 11
0

if fragment within fragment back use this code onbackpreesed method

 @Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if(getFragmentManager().getBackStackEntryCount() == 1) {
        new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("Check out")
                .setMessage("want to do check out?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        closeApp();
                    }
                })
                .setNegativeButton("No",null)
                .show();

    }
    else {
        super.onBackPressed();
    }
}

each fragment store in a stack

 FragmentManager ff=getFragmentManager();
ff.beginTransaction().replace(R.id.main_content,new home()).addToBackStack(null).commit();

it's work in my project

Jigish
  • 221
  • 2
  • 9
  • My fragment is nested fragment and i have written my code in third fragment and want to back press to second fragment. but dont know any how it going to first fragment back event listener. – Jyoti Aug 25 '17 at 12:48
  • in your main activity set OnBackPressed method and when you replace the fragment that time FragmentManager ff=getFragmentManager(); ff.beginTransaction().replace(R.id.main_content,new your fragment name()).addToBackStack(null).commit(); – Jigish Aug 25 '17 at 18:42
  • I am agree with ur answer but what is the situation that on my main activity i have written code of Double back pressed event that is code of exit from application. and my main activity contains four Viewpager tab fragment. and my first tab fragment opens another fragment that is about nested fragment. – Jyoti Aug 26 '17 at 06:18
  • so actually what i want that i want back from my nested fragment to my first tab fragment. but what my nested fragment doing it calling main activity double pressed exit code – Jyoti Aug 26 '17 at 06:20
  • I have edit or posted my Double back press code above in my code. Please let me know if there is any solution for this problem – Jyoti Aug 26 '17 at 06:28
  • 1
    I solved this issue by referring this link https://tausiq.wordpress.com/2014/06/06/android-multiple-fragments-stack-in-each-viewpager-tab/ – Jyoti Aug 26 '17 at 07:50
0

I used this in Activity

Step 1:

Created a global variable for boolean

private boolean doubleBackToExitPressedOnce = false;

Step 2:

Then in onBackPress() method of activity

i did this

@Override
public void onBackPressed() {
    if (mViewPager.getCurrentItem() > 0) {
        //if any tab selected instead of tab 1
        mDoubleBackToExitPressedOnce = false;
    } else if (mViewPager.getCurrentItem() == 0) {
        //if tab 1 selected
        mDoubleBackToExitPressedOnce = true;
        if (mDoubleBackToExitPressedOnce)
            super.onBackPressed();
    }
    mViewPager.setCurrentItem(0);//go to tab 1
}
LEGEND MORTAL
  • 336
  • 3
  • 18
0

I was also Struggling in this regard. after a lot of research i found a solution that we have to call super.onBackPressed() where our last or home fragment is Active

Solution

override fun onBackPressed() {
    val activeFragment  = this.supportFragmentManager.
    findFragmentById(R.id.frame_layout)

    if (activeFragment is HomeFragment){
        startActivity(Intent(this, DashBoardActivity::class.java))
        finish()
        super.onBackPressed()
    }
    else
    {
        val ft: FragmentTransaction 
       =supportFragmentManager.beginTransaction()
      //should not call super.onBackPressed()

      switchFragment(ft)
    }
    //nor here you should call super.onBackPressed()
}

and the switchFragment function is

fun switchFragment(ft:FragmentTransaction) {
    try {
        ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
        if (supportFragmentManager.findFragmentById(R.id.frame_layout) == null) {
            ft.add(R.id.frame_layout, HomeFragment())
        } else {
            ft.replace(R.id.frame_layout, HomeFragment())
            println("Comess")
        }
        ft.addToBackStack(null)
        ft.commit()
    } catch (e: Exception) {
        e.printStackTrace()
    }
}
Noaman Akram
  • 3,680
  • 4
  • 20
  • 37