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

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


当前回答

if片段和使用NavController简单调用

findNavController().popBackStack()

其他回答

我有同样的问题,我为它创建了一个新的侦听器,并在我的片段中使用。

1 -你的活动应该有一个监听器接口和一个监听器列表

你应该实现添加和删除监听器的方法

你应该重写onBackPressed方法来检查监听器是否使用了背按

public class MainActivity ... {

    /**
     * Back press listener list. Used for notifying fragments when onBackPressed called
     */
    private Stack<BackPressListener> backPressListeners = new Stack<BackPressListener>();


    ...

    /**
     * Adding new listener to back press listener stack
     * @param backPressListener
     */
    public void addBackPressListener(BackPressListener backPressListener) {
        backPressListeners.add(backPressListener);
    }

    /**
     * Removing the listener from back press listener stack
     * @param backPressListener
     */
    public void removeBackPressListener(BackPressListener backPressListener) {
        backPressListeners.remove(backPressListener);
    }


    // Overriding onBackPressed to check that is there any listener using this back press
    @Override
    public void onBackPressed() {

        // checks if is there any back press listeners use this press
        for(BackPressListener backPressListener : backPressListeners) {
            if(backPressListener.onBackPressed()) return;
        }

        // if not returns in the loop, calls super onBackPressed
        super.onBackPressed();
    }

}

4 -你的片段必须实现接口的背压

5 -你需要添加片段作为背按的监听器

如果片段使用这个背压,你应该从onBackPressed返回true

7 -重要-你必须删除片段从列表onDestroy

public class MyFragment extends Fragment implements MainActivity.BackPressListener {


    ...

    @Override
    public void onAttach(Activity activity) {
        super.onCreate(savedInstanceState);

        // adding the fragment to listener list
        ((MainActivity) activity).addBackPressListener(this);
    }

    ...

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

        // removing the fragment from the listener list
        ((MainActivity) getActivity()).removeBackPressListener(this);
    }

    ...

    @Override
    public boolean onBackPressed() {

        // you should check that if this fragment is the currently used fragment or not
        // if this fragment is not used at the moment you should return false
        if(!isThisFragmentVisibleAtTheMoment) return false;

        if (isThisFragmentUsingBackPress) {
            // do what you need to do
            return true;
        }
        return false;
    }
}

有一个Stack来代替ArrayList,以便能够从最新的片段开始。在向后台堆栈添加片段时也可能出现问题。所以你需要检查碎片是否可见,而使用背压。否则,其中一个片段将使用事件,并且最新的片段将不会在背按时关闭。

我希望这能解决所有人的问题。

以下是我对这个问题的解决方案:

活动A:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == REQUEST_CODE)
    {
        if(resultCode == Activity.RESULT_OK)
        {
            tvTitle.setText(data.getExtras().getString("title", ""));
        }
    }
}

活动B:

@Override
public void onBackPressed() 
{
    setResult(Activity.RESULT_OK, getIntent());

    super.onBackPressed();
}

活动b保存片段。

在片段:

private void setText(String text)
    {
        Intent intent = new Intent();
        intent.putExtra("title", text);
        getActivity().setIntent(intent);
    }

通过这种方式,活动A中的意图对象“data”将从片段中获取字符串

没有人提到我如何调用活动?这个逻辑中的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方法。

这些都不容易实现,也不会以最佳方式发挥作用。

片段有一个方法调用onDetach来完成这项工作。

@Override
    public void onDetach() {
        super.onDetach();
        PUT YOUR CODE HERE
    }

这个就行了。