Disable onBackPressed only in ONE fragment - Android - java

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.

Related

Removing/replacing fragments

I'm starting to work with fragments and ran into a problem. I have file viewing fragments(more than one) and a search fragment. To make things easier I add my file viewing fragment to backstack whenever I go to search so I could easily pop it back if I decide to just close it. Now the problem is that when I press on file in the search fragment so that I travel to the specific fragment in which that file is, the onCreateView of the first fragment(which was in backstack) always gets called even though I replaced it(?) and I don't want that. Here are things I do to change the fragments on search file press:
1.I call pop to get to previous fragment
#Override
public boolean onSearchViewClose() {
if (getActivity() != null) {
getActivity().getSupportFragmentManager().popBackStack();
return true;
}
return false;
}
2. Then I replace the remaining fragment
public void setFragment(Fragment fragment, String tag, boolean clearBackStack, boolean addToBackStack) {
// Insert the fragment by replacing any existing fragment
hideLoadingProgress();
FragmentManager fragmentManager = getSupportFragmentManager();
if (clearBackStack) {
clearBackStack(fragmentManager);
}
FragmentTransaction transaction = fragmentManager.beginTransaction().replace(R.id.content_frame, fragment, tag);
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.commit();
}
while clearing backstack:
public void clearBackStack(FragmentManager fragmentManager) {
for (int i = 0; i < fragmentManager.getBackStackEntryCount(); ++i) {
fragmentManager.popBackStack();
}
}
Even if I don't clear backstack the problem persists.Thanks for your answers in advance.
The answer was simple - I should've just used getActivity().getSupportFragmentManager().popBackStackImmediate(); when exiting search view as the earlier method didn't work because it waited for program to return to its event loop (asynchronous).

How to Implement onBackPressed for Android Fragments(Tabs Activity)

I am developing an Android Application which contains the Tabs Activity. My Tabs activity contains four tabs(Fragments--[1][2][3][4]). What I want is when I press the Back button it must be redirected to the previous tab, not to the first tab. Like
[4] -> [3]
[3] -> [2]
[2] -> [1]
[1] -> Alert to logout from the App
Please help me out. What do I have to write in my TabsActivity class.
Assumption
Your four fragments is hoted with ViewPager.
Logic
You can write your code into
#Override
void onBackPressed()
{
if(viewPager.getCurrentItem==3)
{
viewPager.setCurrentItem(2)
}
else if{
}
}
and like wise
Use logics instead of hardcoding page numbers.
Below solution works with 2,3,... n, every number of items in Viewpager.
#Override
public void onBackPressed() {
if (viewPager.getCurrentItem() != 0) {
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
} else super.onBackPressed();
}
If you are using TabHost then you can use this solution.
In your attached Activity onBackPressed() you have to implement like below,
#Override
void onBackPressed()
{
if(viewPager.getCurrentItem==3){
viewPager.setCurrentItem(2)
}
else if{
//do your stuff here
}
}

Android Fragment onBackPressed

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();
}
}

back to previous fragment from other fragment

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.

Replace Fragment from OnClickListener

I'm running into trouble. I have a Fragment with an onclicklistener. The fragment calls "ClickMe" which is in my Activity that hosts the fragment. However, in order for ClickMe to not error out, ClickMe has to be static. But, Clickme can't be static because then getFragmentManager errors out. Essentially I'm trying to create a game. A click will put a new fragment over the top of the old one (as you have to do the same thing 10 times in a row in my game. Here's the code:
Fragment:
text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(loc1 == 10 || loc2 ==10){
//Text if user wins
BlankFragment.counter ++;
BlankFragment.ClickMe(BlankFragment.counter);
Log.i("Win: ", "Yay");
}else{
//Text if user loses
Log.i("Lose: ", "Boo");
}
}
});
MainActivity:
public void ClickMe(int count){
Fragment newFragment;
counter = count;
if(counter > 5){
newFragment = new g3by3Fragment();
}else{
newFragment = new g3by3Fragment();
}
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, newFragment);
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
Thank you for your help!
You don't have to preform FragmentTransactions from the Activity. You can just add well preform them from the Fragment. Your detour into the Activity through ClickMe is unnecessary. I know you probably do this because the logic of your game is in the Activity but that is not optimal. Let the Fragments themselves decide which Fragment comes next or implement a Singleton which takes care of your game logic.

Categories

Resources