是否有一种方法,我们可以实现onBackPressed()在Android片段类似的方式,我们实现在Android活动?

因为Fragment的生命周期没有onBackPressed()。在android3.0片段中是否有其他替代方法来覆盖onBackPressed() ?


当前回答

最好的解决方案,

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

            }
        }
    }
}

其他回答

在kotlin中,这要简单得多。

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            //
        }
    })
}

没有人提到我如何调用活动?这个逻辑中的onBackPressed。

所以我创建了一个可能对你有用的扩展:

fun Fragment.onBackClick(callback: (onBackPressedCallback: OnBackPressedCallback) -> Unit) {
// This callback will only be called when MyFragment is at least Started.

    activity?.onBackPressedDispatcher?.addCallback(viewLifecycleOwner) {
        callback.invoke(this)
    }
}

现在激动人心的部分调用onBackPressed当你的逻辑完成:

片段中的示例使用:

onBackClick { 
        if (shouldBackFromFrag){
            //do your logic when pressed back
        }else{
            it.isEnabled = false //the key to disable the dispatcher
            activity?.onBackPressed()
        }
    }

根据@ hammer的回答,这里是伪代码,它应该如何工作。 假设你的主活动名为BaseActivity,它有子片段(就像SlidingMenu库的例子一样)。 以下是步骤:

首先,我们需要创建接口和类,实现它的接口具有泛型方法

Create class interface OnBackPressedListener public interface OnBackPressedListener { public void doBack(); } 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); } } Since now, we will work on our code BaseActivity and its fragments Create private listener on top of your class BaseActivity protected OnBackPressedListener onBackPressedListener; create method to set listener in BaseActivity public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) { this.onBackPressedListener = onBackPressedListener; } in override onBackPressed implement something like that @Override public void onBackPressed() { if (onBackPressedListener != null) onBackPressedListener.doBack(); else super.onBackPressed(); 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; }

瞧,现在当你在片段中单击返回时,你应该捕获你的自定义on back方法。

这是我的答案,处理碎片按下后退按钮。 我有底部导航与五个项目(A, B, C, D,E)附加到活动时,点击一个项目,我附加的片段到活动。 让我们假设点击项目(A),我附加片段(A),然后如果点击项目(B),我附加片段(B),以此类推。

点击项目的流程。A - C > B - > - > D - > E

返回按钮按下的流程。D E - > - > - > C > B

 @Override
        public void onBackPressed() {
            int count = getSupportFragmentManager().getBackStackEntryCount();
            if (count == 0) {
                super.onBackPressed();
            } else {
                int index = ((getSupportFragmentManager().getBackStackEntryCount()) -1);
                getSupportFragmentManager().popBackStack();
                FragmentManager.BackStackEntry backEntry = getSupportFragmentManager().getBackStackEntryAt(index);
                int stackId = backEntry.getId();
                bottomNavigationView.getMenu().getItem(stackId).setChecked(true);
            }
        }

像这样执行 Fragment_1 -> Fragment_2 -> Fragment_3

    Button btn = (Button) rootView.findViewById(R.id.your_button_id);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Fragment_2 nextFrag= new Fragment_2();
            getActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_frame, nextFrag,getTag())
                    .addToBackStack(null)
                    .commit();

        }
    });

Fragment_3 -> Fragment_2 -> Fragment_1

Step_1:在Base Activity中创建一个可公开访问的字符串

step2:每当一个新的Fragment被激活时,在Base Activity中改变String的值

Step_3:然后添加onBackPressed()方法,并将字符串值传递给另一个方法,其中fagments可以被替换

在基础活动中

public static String currentFragment=null;

@Override
public void onBackPressed() 
{
        displayPreviousFragment(currentFragment);
}

public void displayPreviousFragment(String currentFragment)
{
    //creating fragment object
    Fragment fragment = null;

    //initializing the fragment object which is selected
    switch (currentFragment)
    {
        case "Fragment_2"    :   fragment = new Fargment_1();     break;
        case "Fragment_3"    :   fragment = new Fragment_2();     break;
    }

    //replacing the fragment
    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.frame_to_replace_fragment, fragment);
        ft.commit();
    }
}

在Fragment_2 在OnCreateView方法内

BaseActivity.currentFragment="Fragment_2";

在Fragment_3 在OnCreateView方法内

BaseActivity.currentFragment="Fragment_3";