Issue with back button in fragment android - android

I have made in appliction using fragments.First there is a home sreeen in which there is a login button.when user clicks the login button a new fragment is opened which has username and password in it.I have put the loginfragment into backstack so that user can navigate to the home screen.If the user enters the correct credentials in the login frag,main fragments is opened.I have also put the mainfrag so i can navigate back and forth.But now what i want is that when the user is on home screen and if he pressed the back button the app should close but in my case it is going back to login fragment.
For eg
1] if user press login button from home screen
backstack contains "login"
2] now if user enters correct credentials and clicks ok, main frag is opened
backstack contains "main"
"login"
3] now in main frag i have 2 buttons say A and B,now if the user clicks on button A
backstack contains "A"
"main"
"login"
Now what i want is that when user clicks on back button when he is on main frag, the app should finish ,but in my case it goes back to login frag because login is still present in the backstack

EDIT -
Solution 1:
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), Main.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
getActivity().finish();
}
NOTE:
I assume - Home class is your current home screen Class and Main class is your main starting point of the application.
Use Flag Intent.FLAG_ACTIVITY_CLEAR_TOP and call very First page from the Home page.
Solution 2:
If you have only one activity that handles all the fragments then just call,
#Override
public void onClick(View view) {
getActivity().finish();
}

You have to do this :
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
&& !event.isCanceled()) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
return true;
}
return super.onKeyUp(keyCode, event);
}
Say if it is what you want :)

When user clicks back button, first you have get the entry from the stack. If the entry is your main fragment kill the app.
android.os.Process.killProcess(android.os.Process.myPid());
finish();

While you have only login fragment visible(only login fragment at fragment stack), if back button is clicked then you want the activity to be closed?
Solution: Add login fragment to fragment stack without adding it to backstack (without using addToBackStack() method.)
For instance:
Adding a fragment without adding it to backstack:
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
Adding a fragment wiht adding it to backstack:
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Before you call commit(), however, you might want to call
addToBackStack(), in order to add the transaction to a back stack of
fragment transactions. This back stack is managed by the activity and
allows the user to return to the previous fragment state, by pressing
the Back button.
Read more about fragments.

Related

Closed fragment still appearing under base fragment

I have 5 fragments (home, settings, newPost, notifications and profile) inside my Main2Activity.
Inside HomeFragment I have a RecyclerView with a lot of post views, every post containing an "open" button which should open a PostFragment. After the PostFragment is opened I have 3 options to go back to HomeFragment: by tapping phone's 'back' button, tapping my post's XML "back" button or tapping Home from the bottomNavView. The problem is that after PostFragment disappears and my screen goes back to HomeFragment, PostFragment is still observable, but under HomeFragment's RecyclerView. How can I manage that?
This is how I open my PostFragment:
viewHolder.itemView.findViewById(R.id.seePostButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment newFragment = new PostFragment();
FragmentTransaction transaction = ((AppCompatActivity) context).getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_host_fragment, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
UPDATE:
It seems PostFragment will fully disappear if I press back one more time but it's not very efficient.
UPDATE 2.0:
public void onBackPressed(){
getActivity().getSupportFragmentManager().popBackStack();
}
Using this method:
1.if I'm in PostFragment and tap Home, PostFragment remains observable under HomeFragment's RecyclerView
2.if I'm in PostFragment and tap phone's back button, the problem is not happening anymore
3.if I'm in PostFragment and tap posts's XML back button, to problem does not happen anymore
BUT, in my ProfileFragment I have a 2tabs (MyPosts and Posts I've Applied To) TabView connected to a viewPager that contains the posts. If I open one post and tap any of the three options I have mentioned earlier, HomeFragment pops up, having the Post observable under the recyclerView. From this point, any bottomNavItem I tap, the PostFragment will be observable.
HomeFragment with PostFragment being visible between posts:
https://imgur.com/61d6PCd
PostFragment:
https://imgur.com/vZ8omUx
ProfileFragment:
https://imgur.com/TKzgXik
Tapping back from a PostFragment opened from ProfileFragment should get me back to ProfileFragment, not HomeFragment.
UPDATE 3:
I modified onBackPressed() to:
FragmentTransaction transaction =
getActivity().getSupportFragmentManager().beginTransaction();
transaction.remove(this);
transaction.addToBackStack(null);
transaction.commit();
Now if I tap Post's back button (not phone's) the Post is not visible anymore behind the RecyclerView. But if I use phone's back button, the problem is still there. I have to somehow include onBackPressed() in phone's Back button code..
UPDATE: Final edit, problem solved:
Because the Overrideable onBackPressed is only available in the activity that hosts the fragments I had to modify it there like this:
#Override
public void onBackPressed() {
if(getSupportFragmentManager().findFragmentByTag("POST") == null){
super.onBackPressed();
}else{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.remove(getSupportFragmentManager().findFragmentByTag("POST"));
transaction.addToBackStack(null);
transaction.commit();
}
}

Go back main page fragment when user click "done"

I'm trying to go back to main page fragment when user click to 'Done' button. It can be like swifts' "dismiss()" function. However, I dont know what am I using like that function in android.
My code run like; open activity from fragment and this fragment load detail fragment.
First of all, the first fragments' adapter open the second fragments' activity :
Intent intent = new Intent(view.getContext(), DetailActivity.class);
intent.putExtra(Consts.EXTRA_OFFER_DETAIL, binding.getController());
view.getContext().startActivity(intent);
After that, activity open fragment automatically
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container_fragment, new DetailFragment(), null);
transaction.commit();
And I want to close last fragment when user click alert dialogs' done button
builder.setNegativeButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
getActivity().getFragmentManager().popBackStack(); //That is what I tried but doesnt work
}
});
I'm not quite sure about your activity and fragment workflow but to close the whole activity you can just call
finish();
to dismiss the whole activity.
Since there is no fragement in the backstack, popBackStack() won't do anything.
If you only wnat to dismiss the fragement, you should use:
super.onBackPressed();

How to avoid Fragment going back to previous Fragment on pressing device back button?

I am developing an android in which when I pressed device back button I go to previous fragment. What I want to achieve is that when I pressed device back button I don't want to go to previous fragment. How can I achieve that?.
You must be doing calling addtobackstack("name") while adding or replacing the fragment.Remove this function before calling next fragment you wont go back to previous fragment for further desc
Do not add that fragment to backstack of the new fragment you're calling. Look at the below example I've used to explain you how this works.
To make that fragment come again, just add that fragment to backstack which you want to come on back pressed,
Eg:
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new LoginFragment();
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = ((FragmentActivity)getContext()).getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack("SignupFragment");
ft.commit();
}
}
});
In the above case, I m opening a LoginFragment when signIn button is pressed, right now am in SignupFragment. So if I call addToBackStack(TAG), TAG = "SignupFragment", then when back button is pressed in LoginFragment, we come to SignUpFragment.
Happy Coding!

how to clear the fragment stack and activity stack on a button click

There are similar questions, but none of the are solving my issue.
My app flow is following:
Activity home starts Activity B(which does the setup work)
In activity B hosts three screens as fragments...
Fragment1 -> fragment2-> fragment 3.
This is how I make fragments. I am not using replace.just adding it.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = null;
if (getFragType().equals("simple")) {
fragment = new SimpleFragment().newInstance();
}
if (getFragType.equals("inter")) {
if (getFragType.getComponent().equals("con"))
fragment = new SetupConFragment().newInstance();
else if (getFragType.getComponent().equals("ben"))
fragment = new SetupBenageFragment().newInstance();
}
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
Fragment3 has a done button. So once all the 3 steps are done from fragment 3 am launching a new activity C.
The issue is:--
From the activity C , if the user presses the back button, it diplays fragment 2, then fragment 1. Ideally once the user is in Activity C, back press should just exit the screen
I have used all combinations of the intent flags, but it is not helping.
And this is on my button click.
Intent launch = new Intent(mContext, MainActivity.class);
launch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launch.putExtra("Exit me", true);
mContext.startActivity(launch);
((ConfigureActivity)mContext).finish();
Any help will be appreciated.
You can do this way:
Clear Fragment stack:
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
Clear Activity stack:
Intent intent = new Intent(Your_Current_Activity.this, Your_Destination_Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Hope this will help you.
Say, if you want to start Activity B in Activity A but you don't want user to go back to Activity A,
final Intent intent = new Intent(this, ActivityB.class);
startActivity();
finish(); // kill the current activity (i.e., Activity A) so user cannot go back
In your Activity C, you can control Back key by overriding onBackPressed().
#Override
public void onBackPressed()
{
// code here depending on your needs
}

addToBackStack doesn't work, closes the activity instead of popping back fragments

I have a probleam and I can't find a solution anywhere.
My app doesn't return to previous fragment when I press the back button, instead closes the activity.
I have an activity that displays 4 fragment: [1],[2],[3],[4]. I can switch between the first 3 fragments with the action bar, I don't want to add them to the back stack.
Fragment [4] is a detailed view of an item selected in fragment [3]. When I press back in [4] I want to return to fragment [3], not closing the app.
The transitions are done in this way BY THE ACTIVITY in which fragments are placed:
private void replaceFragment(Fragment fragment, boolean toBackStack){
if(fragment != null){
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, fragment);
if(toBackStack)
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
where toBackStack is always false except when the transition is from [3] to [4].
If I pass toBackStack true in every transition, the activity closes anyway.
I had the same problem. Specifically, I am implementing a PreferenceFragment and I want the back button to return me to whatever the previously loaded fragment was.
It appears that the "back stack" is something that is not automatically triggered with the system back button. My solution was to manually pop the back stack from the onBackPressed override:
#Override
public void onBackPressed()
{
if (inSettings)
{
backFromSettingsFragment();
return;
}
super.onBackPressed();
}
Whenever I navigate to my preferences fragment, I set the inSettings boolean to true in the activity to retain that state. Here is what my backFromSettingsFragment method looks like:
private void backFromSettingsFragment()
{
inSettings = false;
getFragmentManager().popBackStack();
}
So, if you are able to track the state of when you are in Fragment [4] and intercept the back button, you should be able to manually call
getFragmentManager().popBackStack();
to go back to Fragment [3].
Note: remember that you need to add Fragment [3] to the back stack, not Fragment[4]. (Unless [4] goes to [5] and you need to back to [4] as well.)

Categories

Resources