How to implement onBackPressed() in Fragments?

2018-12-31 03:15发布

Is there a way in which we can implement onBackPressed() in Android Fragment similar to the way in which we implement in Android Activity?

As the Fragment lifecycle do not have onBackPressed(). Is there any other alternative method to over ride onBackPressed() in Android 3.0 fragments?

30条回答
几人难应
2楼-- · 2018-12-31 04:11

This worked for me: https://stackoverflow.com/a/27145007/3934111

@Override
public void onResume() {
    super.onResume();

    if(getView() == null){
        return;
    }

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
                // handle back button's click listener
                return true;
            }
            return false;
        }
    });
}
查看更多
闭嘴吧你
3楼-- · 2018-12-31 04:11

The solution is simple:

1) If you have a base fragment class that all fragments extend, then add this code to it's class, otherwise create such a base fragment class

 /* 
 * called when on back pressed to the current fragment that is returned
 */
 public void onBackPressed()
 {
    // add code in super class when override
 }

2) In your Activity class, override onBackPressed as follows:

private BaseFragment _currentFragment;

@Override
public void onBackPressed()
{
      super.onBackPressed();
     _currentFragment.onBackPressed();
}

3) In Your Fragment class, add your desired code:

 @Override
 public void onBackPressed()
 {
    setUpTitle();
 }
查看更多
怪性笑人.
4楼-- · 2018-12-31 04:12

According to @HaMMeRed answer here is pseudocode how should it works. Lets say that your main activity is called BaseActivity which has child fragments (like in SlidingMenu lib example). Here are the steps:

First we need create interface and class which implements its interface to have generic method

  1. Create class interface OnBackPressedListener

    public interface OnBackPressedListener {
        public void doBack();
    }
    
  2. Create class which implements skills of OnBackPressedListener

    public class BaseBackPressedListener implements OnBackPressedListener {
        private final FragmentActivity activity;
    
        public BaseBackPressedListener(FragmentActivity activity) {
            this.activity = activity;
        }
    
        @Override
        public void doBack() {
            activity.getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }
    
  3. Since now, we will work on our code BaseActivity and its fragments

  4. Create private listener on top of your class BaseActivity

    protected OnBackPressedListener onBackPressedListener;
    
  5. create method to set listener in BaseActivity

    public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
        this.onBackPressedListener = onBackPressedListener;
    }
    
  6. in override onBackPressed implement something like that

    @Override
    public void onBackPressed() {
        if (onBackPressedListener != null)
            onBackPressedListener.doBack();
        else
            super.onBackPressed();
    
  7. in your fragment in onCreateView you should add our listener

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activity = getActivity();
    
        ((BaseActivity)activity).setOnBackPressedListener(new BaseBackPressedListener(activity));
    
        View view = ... ;
    //stuff with view
    
        return view;
    }
    

Voila, now when you click back in fragment you should catch your custom on back method.

查看更多
墨雨无痕
5楼-- · 2018-12-31 04:12

Best solution,

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;

public class BaseActivity extends AppCompatActivity {
    @Override
    public void onBackPressed() {

        FragmentManager fm = getSupportFragmentManager();
        for (Fragment frag : fm.getFragments()) {
            if (frag == null) {
                super.onBackPressed();
                finish();
                return;
            }
            if (frag.isVisible()) {
                FragmentManager childFm = frag.getChildFragmentManager();
                if (childFm.getFragments() == null) {
                    super.onBackPressed();
                    finish();
                    return;
                }
                if (childFm.getBackStackEntryCount() > 0) {
                    childFm.popBackStack();
                    return;
                }
                else {

                    fm.popBackStack();
                    if (fm.getFragments().size() <= 1) {
                        finish();
                    }
                    return;
                }

            }
        }
    }
}
查看更多
素衣白纱
6楼-- · 2018-12-31 04:14

You should add interface to your project like below;

public interface OnBackPressed {

     void onBackPressed();
}

And then, you should implement this interface on your fragment;

public class SampleFragment extends Fragment implements OnBackPressed {

    @Override
    public void onBackPressed() {
        //on Back Pressed
    }

}

And you can trigger this onBackPressed event under your activities onBackPressed event like below;

public class MainActivity extends AppCompatActivity {
       @Override
        public void onBackPressed() {
                Fragment currentFragment = getSupportFragmentManager().getFragments().get(getSupportFragmentManager().getBackStackEntryCount() - 1);
                if (currentFragment instanceof OnBackPressed) {  
                    ((OnBackPressed) currentFragment).onBackPressed();
                }
                super.onBackPressed();
        }
}
查看更多
回忆,回不去的记忆
7楼-- · 2018-12-31 04:14

According to the AndroidX release notes, androidx.activity 1.0.0-alpha01 is released and introduces ComponentActivity, a new base class of the existing FragmentActivity and AppCompatActivity. And this release brings us a new feature:

You can now register an OnBackPressedCallback via addOnBackPressedCallback to receive onBackPressed() callbacks without needing to override the method in your activity.

查看更多
登录 后发表回答