Fragment back button pressed android

Detect back button but don’t dismiss dialogfragment

I have a dialogfragment for a floating dialog which includes a special keyboard that pops up when a user presses inside an EditText field (the normal IME is stopped from being displayed).

I would like the keyboard to be dismissed (visibility = GONE) when the user presses the back button (just as with a normal IME service) but the dialog to remain visible. However, there does not appear to be a way to do this as far as I can see from my fairly extensive reading on SO and elsewhere.

If I set the dialog to be non-cancelable then I don’t get notified by onCancel() or onDismiss() because the dialog isn’t cancelable.

If I set the dialog to be cancelable then I get notified, but the dialog is dismissed.

I can’t attach an onKeyListener to the dialog in the fragment because it is replaced by the system so that the fragment can handle the dialog’s life cycle.

Is there any way to do this? Or has access to the detection of key events been entirely fenced off for the purposes of the Fragment system?

11 Answers 11

The best way and cleanest way is to override onBackPressed() in the dialog you created in onCreateDialog().

I had the same problem than you and I’ve fixed it attaching the onKeyListener to the dialogfragment.

In the method onResume() of the class that extend of DialogFragment put these piece of code:

Here one of the problems that you can find is this code is going to be executed twice: one when the user press tha back button and another one when he leave to press it. In that case, you have to filter by event:

How has no one suggested this?

As an addendum to Juan Pedro Martinez’s answer I thought it would be helpful to clarify a specific question (one that I had) when looking at this thread.

If you wish to create a new DialogFragment and have it so the user can only cancel it using the back-button, which eliminates random screen touches from canceling the fragment prematurely, then this is the code that you would use.

In what ever code that you call the DialogFragment you need to set the cancelable setting to false so that NOTHING dismisses the fragment, no stray screen touches, etc.

Then, within your DialogFragment, in this case MyDaialogFragment.java, you add the onResume override code to have the dialog listen for the Back Button. When it’s pressed it will execute the dismiss() to close the fragment.

Now your dialog will be called with the «setCancelable» to false, meaning nothing (no outside clicks) can cancel it and shut it down, and allowing (from within the dialog itself) only the back button to close it.

Источник

how to go back to previous fragment on pressing manually back button of individual fragment?

I have only one activity and multiple fragments in my application.

Читайте также:  Как выключить режим для слабовидящих андроид

Two main fragment A(left) and B(right).

All fragments have individual back buttons.

So when I press back button of fragment A1, it should go back to A, similarly when Back button from B2 is pressed, B1 appears and from B1 to B and so on.

How to implement this type of functionality?

10 Answers 10

I have implemented the similar Scenario just now.

Activity ‘A’ -> Calls a Fragment ‘A1’ and clicking on the menu item, it calls the Fragment ‘A2’ and if the user presses back button from ‘A2’, this goes back to ‘A1’ and if the user presses back from ‘A1’ after that, it finishes the Activity ‘A’ and goes back.

See the Following Code:

Activity ‘A’ — OnCreate() Method:

Fragment : ‘A1’

I am replacing the existing fragment with the new Fragment when the menu item click action happens:

Activity ‘A’ — onBackPressed() Method:

Since all the fragments have one parent Activity (which is ‘A’), the onBackPressed() method lets you to pop fragments if any are there or just return to previous Activity.

If you are looking for Embedding Fragments inside Fragments, please refer the link: http://developer.android.com/about/versions/android-4.2.html#NestedFragments

@trueblue’s answer got me going with one minor but annoying issue. When there is only one fragment on the backstack and you press back button, that frame is removed and the app remains active with a blank screen. User needed to press back button one more time to exit the app. I modified the original code to the following in order to handle this situation

When there is only 1 fragment in the backstack, we are basically telling android to move the whole app to back.

Update (and probably a better answer)

So after doing some more reading around this, I found out that you can add fragment manager transactions to back stack and then android handles back presses automatically and in a desired way. The below code snippet shows how to do that

The last line shows how you add a transaction to back stack. This solves back press issue for fragments in most situations except for one. If you go on pressing back button, then eventually you will reach a point when there is only one fragment in the back stack. At this point, you will want to do one of the two things

  1. Remove the activity housing the fragment from the back stack of the task in which activity is running. This is because you do not want to end up with a blank activity
  2. If the activity is the only activity in the back stack of the task, then push the task in background.

In my case, it was the later, so I modified the overridden onBackPressed method from my previous answer to look like below

This code is simpler because it has less logic and it relies on framework than on our custom code. Unfortunately I did not manage to implement code for first situation as I did not need to.

Источник

In Fragment on back button pressed Activity is blank

I have an Activity and many fragments inflated in same FrameLayout

example: mainActivity > any fragment (press back button) > activity is blank.

Читайте также:  Лучший андроид камерофон 2021

When I start a fragment:

I suppose I need to make the frameLayout’s visibility GONE again on back pressed, but how do I do this?

I tried onBackPressed and set layout.setVisibility(View.GONE); but I cannot go back through fragments, as I go directly to main page.

11 Answers 11

If you have more than one fragment been used in the activity or even if you have only one fragment then the first fragment should not have addToBackStack defined. Since this allows back navigation and prior to this fragment the empty activity layout will be displayed.

But for the other fragment you need to have this defined otherwise the back will not navigate to earlier screen (fragment) instead the application might shutdown.

To add a fragment

Sorry for the late response.

You don’t have to add ft.addToBackStack(null); while adding first fragment.

If you want to track by the fragments you should override the onBackPressed method, like this

You can override onBackPressed and check to see if there is anything on the backstack.

Just don’t add the first fragment to back stack

Here is the Kotlin code that worked for me.

On a recent personal project, I solved this by not calling addToBackStack if the stack is empty.

Here’s my full implementation:

irscomp’s solution works if you want to end activity when back button is pressed on first fragment. But if you want to track all fragments, and go back from one to another in back order, you add all fragments to stack with:

and then, add this to the end of onCreate() to avoid blank screen in last back pressed; you can use getSupportFragmentManager() or getFragmentManager() depending on your API:

Final words: I don’t suggest you to use this solution, because if you go from fragment1 to fragment 2 and vice versa 10 times, when you press back button 10 times it will do it in back order which users will not want it.

Источник

Fragment pressing back button

I am now having an activity containing fragments

If pressing buttons , [3] , it can be redirected to [4]

I would like to implement the back button as shown follow..

when pressing back at [4] , it return to [3]

when pressing back at [3] , it return to [2]

when pressing back at [1] , the activity finishes();

When it comes to the current implementation, it finish the activity instead of popping up the Fragment. Would you please tell me what I should do or keep in mind ?

17 Answers 17

This worked for me.

-Add .addToBackStack(null) when you call the new fragment from activity.

-Add onBackPressed() to your activity

Easiest way ever:

onResume():

Edit 1: If fragment having EditText .

onCreateView():

onResume():

Note: It will work if you have EditText in fragment.

Done

This is a working solution for me:

Edit: You can replace dialog with getView() for fragments.

Try this simple solution:

In your activity implement onBackPressed

This will work if you want to pop the top fragment on each back press. Note:- While adding fragment to activity always do add the transaction to back stack for this to work

You can use this .. Worked for me..

It seems as though fragment [3] is not removed from the view when back is pressed so you have to do it manually!

Читайте также:  Which was the first android phone

First of all, dont use replace() but instead use remove and add separately. It seems as though replace() doesnt work properly.

The next part to this is overriding the onKeyDown method and remove the current fragment every time the back button is pressed.

In your onCreate() in your activity housing your fragments add a backstack change listener like so:

(Nb. my fragmentManager is declared global) Now every time you change fragment the currentFragment String will become the name of the current fragment. Then in the activities onBackPressed() you can control the actions of your back button as so:

I can confirm that this method works for me.

Update : Kotlin

Still better solution could be to follow a design pattern such that the back-button press event gets propagated from active fragment down to host Activity. So, it’s like.. if one of the active fragments consume the back-press, the Activity wouldn’t get to act upon it, and vice-versa.

One way to do it is to have all your Fragments extend a base fragment that has an abstract ‘boolean onBackPressed()’ method.

Keep track of active fragment inside your Activity and inside it’s onBackPressed callback write something like this

This post has this pattern described in detail

What I do in this cases is I implement the onBackPressed() function from the Activity:

How this works for you too.

Solution for Pressing or handling back button in Fragment.

The way I solved my issue I am sure it will helps you too:

1.If you don’t have any Edit Text-box in your fragment you can use below code

Here MainHomeFragment is main Fragment (When I press back button from second fragment it will take me too MainHomeFragment)

2.If you have another fragment named as Somefragment and it has Edit text-box then you can do it by this way.

Источник

Android Fragment handle back button press [duplicate]

I have some fragments in my activity

And on Back Button Press I must to return from [2] to [1] if current active fragment is [2], or do nothing otherwise.

What is the best practise to do that?

EDIT: Application must not return to [2] from [3]. [6]

25 Answers 25

When you are transitioning between Fragments, call addToBackStack() as part of your FragmentTransaction :

If you require more detailed control (i.e. when some Fragments are visible, you want to suppress the back key) you can set an OnKeyListener on the parent view of your fragment:

I’d rather do something like this:

if you overide the onKey method for the fragment view you’re gonna need :

Use addToBackStack method when replacing one fragment by another:

Then in your activity, use the following code to go back from a fragment to another (the previous one).

If you want to handle hardware Back key event than you have to do following code in your onActivityCreated() method of Fragment.

You also need to check Action_Down or Action_UP event. If you will not check then onKey() Method will call 2 times.

Also, If your rootview(getView()) will not contain focus then it will not work. If you have clicked on any control then again you need to give focus to rootview using getView().requestFocus(); After this only onKeydown() will call.

Источник

Оцените статью