I have a MainActivity, which starts fragments, in according to a specific button pressed. When I'm under a fragment and I press the back button, the application will be closed. My idea is, when the back button is pressed, I will show the MainActivity, with all the button. I write these lines of code in the MainActivity:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
recreate();
}
return super.onKeyDown(keyCode, event);
}
Is it a good solution ? It works quite well, the only things is that between the transaction of fragment layout and the activity layout, there is a black screen for less then half second. is there any way to fix it ?
When you are adding the fragment, add it to backStack. The back press will automatically revert the fragment and shows your main activity.
Eg:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(..............);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Related
This question already has answers here:
White screen after going back through Fragments
(2 answers)
Closed 6 years ago.
I have a MainActivity, it has a lots of Fragment under it.
I set the return mechanism transaction.addToBackStack(null);
The function like this:
public void switchFragment(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.mainFrame, fragment, null);
transaction.addToBackStack(null);
transaction.commit();
}
My issue is when I click the back button to the end, the FrameLayout is white
I tried to add
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mainFrame==null)
return super.onKeyDown(keyCode, event);
}
}
It's not working. How do I avoid this white screen when I call back the Fragment to the end ? Any help would be great!
I took #ReazMushed's suggestion and changed like this:
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() ==1) {
finish();
}else{
super.onBackPressed()
}
}
And the white screen problem is gone!
From your question what I've understood is, you have a set of Fragment which is launched one after one and when you press the back button, they disappears one after one. When the first Fragment reaches and you click the back button again, it shows a white screen.
If I'm correct, you might have to track if the first Fragment is reached and then finish the Activity.
Implement the onBackPressed function in your MainActivity. You might consider doing something like this.
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
getSupportFragmentManager().popBackStack();
else
finish(); // Finish the activity
}
if I launch a full-screen dialog like such
FragmentManager fragmentManager = getActivity().getFragmentManager();
DialogStyleCreator editor = new DialogStyleCreator();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.add(android.R.id.content, editor).commit();
How can I make it so that if I hit the android back arrow (in the top left of the menu) or the back button it closes the dialog instead of going back to the previous activity like in alert dialogs?
You may simply put your transaction in stack of fragment manager and override the function of back button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (Integer.parseInt(android.os.Build.VERSION.SDK) > 5
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
// Simply pop back your fragment stack here
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
// Simply pop back your fragment stack here
}
Since you have added the DialogFragment as transaction.add(android.R.id.content, editor).commit(); you may not have option to listen the dismiss call back.
I suggest you to create the DialogFragment instance and start it like
fm.beginTransaction().add(sampleDialog, "Dialog").commit();
and set the call back interface for Activity Back Button Click and call dismiss();
I'm writing an android application using a FrameLayout and Fragments as its component.
I have 3 fragments: CommunityFragment, TaskFormFragment, TaskFragment.
In CommunityFragment, user presses a button to create a task. Then TaskFromFragment replaces with CommunityFragment in the FrameLayout with addToBackStack. Because after that, I want to return to CommunityFragment with back button.
In TaskFormFragment, user presses create button to create the task. Then TaskFragment opens without addToBackStack because I don't want to show TaskFormFragment when back button is presssed.
All of them working perfect. When I press back button in TaskFragment, CommunityFragment is shown. However, after that point, if I open TaskFormFragment and press back button, it doesn't show CommunityFragment! Instead, it opens TaskFragment.
How this can happen? Here is my fragment transition code:
From CommunityFragment to TaskFormFragment:
TaskFormFragment newFragment = new TaskFormFragment();
Bundle args = new Bundle();
args.putLong("taskTypeId", taskTypeId);
args.putLong("communityId", community.getId());
newFragment.setArguments(args);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
From TaskFormFragment to TaskFragment:
TaskFragment newFragment = new TaskFragment();
Bundle args = new Bundle();
args.putLong("taskId", task.getId());
newFragment.setArguments(args);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, newFragment);
transaction.commit();
EDIT: I found the solution in this entry: Problems with Android Fragment back stack
I've found the solution in another post. I've added that methods into my Activity class which contains the FrameLayout:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
this.finish();
return false;
} else {
getSupportFragmentManager().popBackStack();
removeCurrentFragment();
return false;
}
}
return super.onKeyDown(keyCode, event);
}
public void removeCurrentFragment() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment currentFrag = getSupportFragmentManager().findFragmentById(R.id.detailFragment);
if (currentFrag != null)
transaction.remove(currentFrag);
transaction.commit();
}
The description and the solution of this problem is here:
Problems with Android Fragment back stack
Once the user presses back in Task fragment and it goes back to community fragment, you should clear your backstack. Your problem is that it is not cleared so when you press back you go to a previous transaction.
EDIT:
So before your community fragment is replaced run this
for(int i =0;i<fragmentmanager.getBackStackEntryCount();i++){
fragmentmanager.popbackstack();
}
See if that fixes it
I want to go back to another fragment by pressing the back button. I already read, that the addToBackStack (String tag) should help but it didn't really work.
Here is what I'm doing when switching fragments.
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
ft.replace(R.id.content_frame, new MainFragment());
ft.addToBackStack("Mainfragment");
ft.commit();
So now, the Fragment opens, and starts an AsyncTask where a loading circle appears. After the loading the data gets displayed. When I now press the back button once, the fragment goes back to the start of the AsyncTask where the loading circle is created. But the AsyncTask doesn't continue. When I press the back button again, the app closes.
I tried to add onBackPressed but it just told me, that this won't work in a Fragment. What would be the best way to go here?
Edit for clarification:
There's no error. It's just not working. It is like I don't even have the line addToBackStack –
I had the same situation before and I ended up with this solution. When you add or replace the Fragments, you need to add it to the backStack with a unique name. Then when the back button is pressed you can see which fragment was the active one with the method below inside the FragmentActivity that you created the Fragment.
private String getCurrentFragmentName() {
int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
String fragmentName;
if (backStackEntryCount > 0) {
fragmentName = getSupportFragmentManager().getBackStackEntryAt(backStackEntryCount - 1).getName();
} else {
fragmentName = "";
}
return fragmentName;
}
and in on onKeyDown() method do the following.
if (keyCode == KeyEvent.KEYCODE_BACK && getCurrentFragmentName().equals("your fragment name")) {
// Handle back press for this case.
return true;
} else if (keyCode == KeyEvent.KEYCODE_BACK
&& getCurrentFragmentName().equals("your another fragment")) {
// Handle back press for another Fragment
return true;
} else {
return super.onKeyDown(keyCode, event);
}
And this is the Place how I add the Fragment with backStack
transaction.addToBackStack("Your Fragment Name");
I want to go back to the last fragment in the back stack, so I want to make the back button popback the stack. Should I do this? and if so, should I override onBackPressed() or onKeyDown()?
#Override
public void onBackPressed()
{
Intent intent = new Intent(this,ABC.class);
startActivity(intent);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
// do something on back.
return true;
}
return super.onKeyDown(keyCode, event);
}
My fragments aren't being added to the back stack properly for some reason
I am using this to try to go back to the previous fragment, but the order is acting strange. What exactly should I do to make the order proper?
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft){
if(teamsFrag !=null)
{
if(manage.getBackStackEntryCount() > 0)
manage.popBackStack(manage.getBackStackEntryAt(manage.getBackStackEntryCount()-1).getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
//ft.detach(dataFrag);
}
Short answer? No.
Long answer? If you have to ask, No.
You should set your fragments up using the fragment manager so that the back button does what you want. You shouldn't override the back button instead of implementing your stack correctly.
I want to go back to the last fragment in the back stack, so I want to make the back button popback the stack.
This is the default behavior when you use FragmentTransaction#addToBackStack() while adding new Fragments with the FragmentManager.