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

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


当前回答

在活动生命周期中,当我们使用FragmentActivity或AppCompatActivity时,总是android返回按钮处理FragmentManager事务。要处理backstack,我们不需要处理它的backstack计数或标记任何东西,但我们应该在添加或替换片段时保持专注。请找到以下片段来处理后退按钮的情况,

    public void replaceFragment(Fragment fragment) {

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!(fragment instanceof HomeFragment)) {
            transaction.addToBackStack(null);
        }
        transaction.replace(R.id.activity_menu_fragment_container, fragment).commit();
    }

在这里,我不会为我的主页片段添加回堆栈,因为它是我应用程序的主页。如果将addToBackStack添加到HomeFragment,那么应用程序将等待删除活动中的所有片段,然后我们将得到空白屏幕,所以我保持以下条件,

if (!(fragment instanceof HomeFragment)) {
            transaction.addToBackStack(null);
}

现在,你可以看到之前添加的片段在活动和应用程序将退出时,到达HomeFragment。您还可以查看以下片段。

@Override
public void onBackPressed() {

    if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
        closeDrawer();
    } else {
        super.onBackPressed();
    }
}

其他回答

if片段和使用NavController简单调用

findNavController().popBackStack()

从你的片段,就用

 requireActivity().onBackPressed();

请单击add binding.actionABack进行处理。setOnClickListener(v -> requireActivity().onBackPressed());

在mainActivity实现回调接口中

protected mainActivity.OnBackPressedListener onBackPressedListener;

public interface OnBackPressedListener {
    void doBack();
}

public void setOnBackPressedListener(mainActivity.OnBackPressedListener onBackPressedListener) {
    this.onBackPressedListener = onBackPressedListener;
}

@Override
public void onBackPressed() {
    if (onBackPressedListener != null) {
        onBackPressedListener.doBack();
    } else { 
        super.onBackPressed();
    }
}

在片段实现接口OnBackPressedListener,我们写在mainActivity

implements mainActivity.OnBackPressedListener

mainActivity是我的基本活动,在你的片段onCreateView方法中编写以下代码

((mainActivity) getActivity()).setOnBackPressedListener(this);

并实现OnBackPressedListener接口方法doBack

@Override
public void doBack() {
    //call base fragment 
}

现在使用doBack()方法调用你想要调用的fragment

根据@ 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方法。

使用导航组件,你可以这样做:

Java

public class MyFragment extends Fragment {

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // This callback will only be called when MyFragment is at least Started.
    OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
        @Override
        public void handleOnBackPressed() {
            // Handle the back button event
        }
    });
    requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);

    // The callback can be enabled or disabled here or in handleOnBackPressed()
}
...
}

科特林

class MyFragment : Fragment() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // This callback will only be called when MyFragment is at least Started.
    val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
        // Handle the back button event
    }

    // The callback can be enabled or disabled here or in the lambda
}
...
}