I have main activity and 2 fragments on it, fragment1 call fragment2
When I am clicking the back button from the built in android buttons it call the onBackPressed function that I overrided in the main activity and exit me from the app.
I want that when I click back on the fragment 2 the onBackPressed of the main activity will not called and it will back me to fragment 1.
The back button of the action bar works well (I think it mean that the backstack is ok).
I tried to do:
getActivity().getSupportFragmentManager().beginTransaction().addToBackStack("Messages");
on the fragment 2
And tried to add
getSupportFragmentManager().popBackStack();
to the onBackPressed() of the main activity
It dosen't did nothing
Thank you
EDIT:
I am trying to do
public void onBackPressed() {
// getSupportFragmentManager().popBackStack();
android.support.v4.app.Fragment fragment2 = getSupportFragmentManager().findFragmentByTag(null);
if (fragment2 != null && fragment2.isVisible()) {
getSupportFragmentManager().popBackStack();
return;
}
and before any show
getSupportFragmentManager().beginTransaction().addToBackStack(null).commit();
tr.show(Fragment2);
but got null on the findFragment(null)
EDIT:
I checked getSupportFragmentManager().beginTransaction().mTail.fragment and saw that the value is the Fragment 1 that I want to be showed, but when I do getSupportFragmentManager().popBackStack(); it dosen't nothing.
Override onBackPressed() in Main activity.
Check the currently displayed fragment, if fragment2 is displayed, then pop back stack.
example:
#Override
public void onBackPressed() {
Fragment fragment2 = getFragmentManager().findFragmentByTag("tag");
if (fragment2 != null && fragment2.isVisible()) {
getFragmentManager().popBackStack();
} else {
finish();
}
}
just use below way; in your Activity check this
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Fragment fragment = getSupportFragmentManager().findFragmentByTag("SecondFragment");
if (fragment instanceof SecondFragment) {
// show first fragment
}else{
// finish();
}
}
i have used findFragmentByTag, you can also use findFragmentById
i agree with #Minhtdh comment but it only applicable if you replace one over other
Before calling fragment2.show() in the MainActivity, add the fragmnet transaction to backstack. There is no need to override onBackPressed().By default android implements the same functionality for you.
simple working code.
to get back to 1st fargment.
yourviewvariable.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
Sorry that I miss typed, I mean method onBackPressed.
But for your case, because you use FragmentTransition.show(), it will not add the fragment to backstack and popBackStack won't work. So I think you should try this:
1. don't called getSupportFragmentManager().beginTransaction().addToBackStack(null).commit(); because it add an unnecessary backstack.
2. don't store the "tr" variable as global variable, and you also need call commit() to end the transaction:
Fragment2.setTag("fragment2");
getSupportFragmentManager().beginTransaction().show(Fragment2).commit();
3. in onBackPressed():
android.support.v4.app.Fragment fragment2 = getSupportFragmentManager().findFragmentByTag("fragment2");
if (fragment2 != null && fragment2.isVisible()) {
getSupportFragmentManager().beginTransaction().hide(fragment2).commit();
return;
} else {
super.onBackPressed();
}
Hope this help.
Related
I am writing a code for onBackPressed() method.
Actually, I want that if the user click on back press it check that If the RecyclerView is visible then it should just close the RecyclerView or if it is invisible it should go to another activity.
How I can do it ? Thanks
Simple you can check the visibilty of the recyclerView like
if ( recyclerView.getVisibility() == View.VISIBLE )
and can can decision what you want to do.
For Example: You have to #Override onBackPressed() function to manage your logic like this:
#Override
public void onBackPressed() {
if (recyclerView.getVisibility() == View.VISIBLE) {
//do it here when recyclerview in visible
} else {
//go to any activity or
//simply supper method will take you on previous activity
super.onBackPressed();
}
}
Assume you have done something like recyclerView = findViewById(R.id.something) already.
#Override
public void onBackPressed() {
if (recyclerView.getVisibility() == View.VISIBLE) {
recyclerView.setVisibility(View.INVISIBLE);
} else {
super.onBackPressed();
}
}
As suggested by #bruno above, actually you have the answer in mind already. All you have to do is implement it and see if it works.
Im trying with no success to disable the back key only in one fragment, in the first one.
I did the override of the onBackPressed method on the Activity that contains the fragment with this:
#Override
public void onBackPressed() {
if (this.fragmentManager.getBackStackEntryCount() > 1) {
//getFragmentManager().popBackStack();
super.onBackPressed();
} else {
//super.onBackPressed();
}
}
So, it works perfectly. BUT when i finish all the path of fragments, at the final fragment i have a button that take me back to the first fragment. I will paste the code where i load this fragment again.
for (Fragment fragment1:getSupportFragmentManager().getFragments()) {
getSupportFragmentManager().beginTransaction().remove(fragment1).commit();
}
MontoFragment montoFragment = new MontoFragment();
cargarFragment(montoFragment);
And here the "cargarFragment()" method
public void cargarFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.animation_slide_in,R.anim.animation_slide_out);
fragmentTransaction.replace(R.id.layoutContenedorFragments,fragment);
fragmentTransaction.addToBackStack(null).commit();
}
After i complete all the fragments and i go back to the first one with that, my onBackPressed method doesnt work anymore, because this.fragmentManager.getBackStackEntryCount() > 1 now is 5 or 6 i dont remember now. And this make the back key enable.
So i dont know what to do.
Thanks!
I just achieve it with this code
#Override
public void onBackPressed() {
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.layoutContenedorFragments);
if (currentFragment instanceof MontoFragment){
}else{
super.onBackPressed();
}
}
i got the current fragment and if this one is an instanceOf That Fragment just do nothing but if not just do the normal onBackPressed.
I look that it works great
try to use popBackStack, replace code block:
for (Fragment fragment1:getSupportFragmentManager().getFragments()) {
getSupportFragmentManager().beginTransaction().remove(fragment1).commit();
}
MontoFragment montoFragment = new MontoFragment();
cargarFragment(montoFragment);
by
void popFragments(int number) {
for (int i = 0, i < number, i++) {
supportFragmentManager.popBackStackImmediate()
}
}
number here is the number of fragments you want to remove, ex: we have fragment 1,2,3,4, so when we are in fragment 4 and want to back to fragment 1, so the number will be 3.
my fragment transition is happened very weirdly. I am trying to open up new fragment upon back button is pressed:
//removed code
Then, when I am at home fragment, without me back press again, it will close the apps:
// removed code
I don't understand why switching from one fragment to another shares the same onKey? As in isn't it supposed to be behave like this: I back press in fragment 2, open up home fragment, inside home fragment I back press again, then it closes the apps.
Currently it's working like this: fragment 2 back press, open up home fragment, without me touching any thing, it goes into the onKey in home fragment.
Any ideas? Thanks in advance.
Remove finish call "getActivity().finish();" then try...
v.setFocusableInTouchMode(true);
v.requestFocus();
v.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if( keyCode == KeyEvent.KEYCODE_BACK ) {
getActivity().moveTaskToBack(true);
return true;
} else {
return false;
}
}
});
If not then try another solution...Add this method in your parent activity.
#Override
public void onBackPressed() {
FragmentManager fragmentmanager = getSupportFragmentManager();
if(fragmentmanager.getBackStackEntryCount() > 0){
fragmentmanager.popBackStack();
} else{
finish();
}
}
I am simply trying to click back and navigate to my previous activity. My flow is this: I go to news_feed activity -> Comments activity -> User Profile activity -> click back (Go to Comments activity) -> click back (This does nothing for some reason) -> Click back (Go back to news_feed activity). I'm not sure why I have to click back twice when I try to go from Comments activity back to news_feed activity. If I go from news_feed activity -> Comments -> press back (Go to news_feed activity) this works perfectly. Here is my code:
news_feed.java:
#Override
public void onBackPressed() {
super.onBackPressed();
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
Comments.java:
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
UserProfile.java:
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(UserProfile.this, Comments.class);
Bundle bundle = new Bundle();
bundle.putString("postId", postId);
bundle.putString("posterUserId", posterUserId);
bundle.putString("posterName", posterName);
bundle.putString("postStatus", postStatus);
bundle.putString("postTimeStamp", postTimeStamp);
bundle.putString("postTitle", postTitle);
intent.putExtras(bundle);
startActivity(intent);
finish();
}
I don't think navigating to these activities would change anything, but I can include the intents that I used to navigate to these activities also if necessary. Otherwise I just included the onBackPressed code that I had for these activities. Any ideas why this might cause a problem? Any help would be appreciated. Thanks.
In your UserProfile class, in onBackPressed() method, you are starting the Comments class again. Why do you have to do this?
What is happening is, you are starting a new Comments activity onBackPressed() of the USerProfile class, so there are two instances of Comments Activity. So you feel you are pressing back btn twice.
If you have to pass data back to Comments from UserProfile class, then make use of setResult() method.
This will be of help
How to pass data from 2nd activity to 1st activity when pressed back? - android
Sending data back to the Main Activity in android
I you want to send back the result to previous activity the start activity by using
startActivityForResult()
insead of
startActivity()
and don't override
onBackPressed()
You can try something like this:
private boolean clicked;
#Override
public void onBackPressed() {
if (!clicked) { // if it was not clicked before, change the value of clicked to true and do nothing directly return, if clicked again, then it will be finish the activity.
clicked=true;
return;
}
super.onBackPressed();
}
And if you are going to use the time, then you can do like this:
private long lastClicked;
#Override
public void onBackPressed() {
if (System.currentTimeMillis() - lastClicked < 1000) { // within one second
super.onBackPressed();
}
lastClicked = System.currentTimeMillis();
}
You don't need to override onBackPressed() if all you're going to do is call startActivity() and finish() in the current activity. The Android backstack will handle both of those for you. Moreover, in your UserProfile.java you are passing data to previous activity. For this, you should use startActvityForResult() in the Comments activity (i.e the previous activity) instead of startActivity().
To learn more about startActvityForResult() visit: https://developer.android.com/training/basics/intents/result.html
public void onBackPressed() {
if (this.lastBackPressTime < System.currentTimeMillis() - 2000) {
this.lastBackPressTime = System.currentTimeMillis();
} else {
//super.onBackPressed(); for exit
//INTENT HERE TO YOUR SECOND ACTIVITY like below
Intent intent=new Intent(A.this,B.class);
startActivirty(intent);
}
}
Create a global variable
private long lastBackPressTime = 0;
Hope this will help you,Let me know..
I have an activity Activity1 with 2 fragments. Everything's working fine but I have one issue :
when I quit the current activity -Activity1- (without calling finish ()) and go to another Activity2, then I click on the backButton on the last activity I go back to the Activity1 and this onResume method is executed
onResume Activity1 code :
#Override
protected void onResume () {
super.onResume ();
fragmentManager.beginTransaction ().replace (
R.id.my_frame_container,
fragmentFactory.getFragment (Fragment1)
).commit ();
}
onResume Fragment1 code :
#Override
public void onResume () {
super.onResume ();
Log.e ("onResume ", " Yes ");
}
From the Documentation : the onResume method of the fragment is called when the onResume method of the activity is too.
However in my case the onResume of the Fragment is not called when I get back to the activity.
Do you have any idea how can I execute fragment code when the onResume of the activity is called ? Thank you.
Since Fragment.onResume tied to Activity.onResume of the containing activity, this method won't get called when we switch between fragments, so you need to call it yourself using OnBackStackChangedListener as follow
getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() {
public void onBackStackChanged() {
FragmentManager fm = getSupportFragmentManager();
if (fm != null) {
int bseCount = fm.getBackStackEntryCount();
if (bseCount > 0) {
Fragment fragment = fm.getFragments().get(bseCount - 1);
fragment.onResume();
}
}
}
});