处理Android导航组件中的后退按钮


82

我想知道如何使用导航控制器正确处理系统后退按钮动作。在我的应用程序中,我有两个片段(例如fragment1和fragment2),并且我在fragment1中有一个动作,目的地为fragment2。除一件事情外,其他所有东西都运行良好-当用户在fragment2中按下系统后退按钮时,我想显示一个对话框(例如,使用DialogFragment)以确认退出。实施此行为的最佳方法是什么?如果我app:defaultNavHost="true"在主机片段中使用它,它将自动返回,而忽略我的规则。而且,此组件的作用是什么?

在此处输入图片说明

我应该使用“ pop to”吗?


1
使用“弹出至”,您可以定义单击后退/上移按钮时的去向(目的地)。
Alex

@Alex因此,如果将其设置为none,它将如何对后退按钮做出反应?
基里尔·特卡奇(Kiryl Tkach)

1
如果将其设置为“ none”,则行为是默认的,该用户将导航到先前的目的地(片段1)
Alex

@Alex,好的,有没有办法按第二个片段处理后退按钮?
基里尔·特卡奇(Kiryl Tkach)

Answers:


146

最新更新-2019年4月25日

新版本androidx.activity ver。1.0.0-alpha07带来了一些变化

Android官方指南中的更多说明:提供自定义后退导航

例:

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

旧更新

UPD:2019年4月3日

现在将其简化。更多信息在这里

例:

requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), this);

@Override
public boolean handleOnBackPressed() {
    //Do your job here
    //use next line if you just need navigate up
    //NavHostFragment.findNavController(this).navigateUp(); 
    //Log.e(getClass().getSimpleName(), "handleOnBackPressed");
    return true;
    }

不推荐使用(自1.0.0-alpha06版本2019年4月3日起):

既然这样,就可以使用片段中的JetPack 实现OnBackPressedCallback并将其添加到活动中来实现: getActivity().addOnBackPressedCallback(getViewLifecycleOwner(),this);

您的片段应如下所示:

public MyFragment extends Fragment implements OnBackPressedCallback {

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        getActivity().addOnBackPressedCallback(getViewLifecycleOwner(),this);
}
    
    @Override
    public boolean handleOnBackPressed() {
        //Do your job here
        //use next line if you just need navigate up
        //NavHostFragment.findNavController(this).navigateUp(); 
        //Log.e(getClass().getSimpleName(), "handleOnBackPressed");
        return true;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().removeOnBackPressedCallback(this);
    }
}

UPD: 您的活动应扩展为AppCompatActivityFragmentActivity在Gradle文件中:

 implementation 'androidx.appcompat:appcompat:{lastVersion}'

4
Jetpack是否仍然存在?
布莱恩·布莱斯

1
如果您的AppCompat活动不是来自支持库,而是来自androidX库,那么是的,您应该
Jurij Pitulja

3
使用AndroidX AppCompatActivity和Androidx Fragment,我也不认为这是可用选项
Omega142

3
OnBackPressedCallback现在是一个抽象类!因此,此解决方案不适用于我。
Junia Montana

3
在执行了on-handleIOnBackPressed()逻辑后,如何进行正常的后退操作?
krishnakumarcn

21

所以,我创建了一个界面

public interface OnBackPressedListener {
    void onBackPressed();
}

并由需要处理后退按钮的所有片段来实现。在主要活动中,我重写了onBackPressed()方法:

@Override
public void onBackPressed() {
    final Fragment currentFragment = mNavHostFragment.getChildFragmentManager().getFragments().get(0);
    final NavController controller = Navigation.findNavController(this, R.id.nav_host_fragment);
    if (currentFragment instanceof OnBackPressedListener)
        ((OnBackPressedListener) currentFragment).onBackPressed();
    else if (!controller.popBackStack())
        finish();

}

因此,如果我的导航主机的顶部片段实现了OnBackPressedListener接口,则将其称为onBackPressed()方法,而在其他地方,我仅会弹出回栈并如果后栈为空则关闭应用程序。


22
一个体面的解决方案。虽然我总是想知道导航组件如果缺少现成的功能,那又有什么意义呢?
First_Strike

检查@Jurij Pitulja答案是去了解这个问题的推荐方法
米奇

为什么我们需要一个单独的接口而不是使用Jetpack中的接口?
IgorGanapolsky

@IgorGanapolsky在回答此问题时,Jetpack中没有接口。
Kiryl Tkach

@KirylTkach mNavHostFragment的声明是什么?
E.Akio '20年

16

建议的方法是一种添加OnBackPressedCallback到活动的OnBackPressedDispatcher

requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) { 
    // handle back event
}

1
如果还像这样传递回调的所有者,则更好.addCallback(viewLifecycleOwner) {},否则即使片段被销毁,您也将继续接收回调。
Marat

13

对于任何寻求Kotlin实现的人,请参见下文。

请注意 OnBackPressedCallback似乎唯一的方法是为内置软件/硬件后退按钮提供自定义后退行为,而不是在操作栏/工具栏中将后退箭头按钮/主页设为向上按钮。为了也覆盖actionbar / toolbar后退按钮的行为,我提供了适用于我的解决方案。如果这是一个错误,或者您知道针对该情况的更好解决方案,请发表评论。

build.gradle

...
implementation "androidx.appcompat:appcompat:1.1.0-rc01"
implementation "androidx.navigation:navigation-fragment-ktx:2.0.0"
implementation "androidx.navigation:navigation-ui-ktx:2.0.0"
...

MainActivity.kt

...
import androidx.appcompat.app.AppCompatActivity
...

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_main)

        ...

        val navController = findNavController(R.id.nav_host_fragment)
        val appBarConfiguration = AppBarConfiguration(navController.graph)

        // This line is only necessary if using the default action bar.
        setupActionBarWithNavController(navController, appBarConfiguration)

        // This remaining block is only necessary if using a Toolbar from your layout.
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        toolbar.setupWithNavController(navController, appBarConfiguration)
        // This will handle back actions initiated by the the back arrow 
        // at the start of the toolbar.
        toolbar.setNavigationOnClickListener {
            // Handle the back button event and return to override 
            // the default behavior the same way as the OnBackPressedCallback.
            // TODO(reason: handle custom back behavior here if desired.)

            // If no custom behavior was handled perform the default action.
            navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
        }
    }

    /**
     * If using the default action bar this must be overridden.
     * This will handle back actions initiated by the the back arrow 
     * at the start of the action bar.
     */
    override fun onSupportNavigateUp(): Boolean {
        // Handle the back button event and return true to override 
        // the default behavior the same way as the OnBackPressedCallback.
        // TODO(reason: handle custom back behavior here if desired.)

        // If no custom behavior was handled perform the default action.
        val navController = findNavController(R.id.nav_host_fragment)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }
}

MyFragment.kt

...
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
...

class MyFragment : Fragment() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val onBackPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // Handle the back button event
            }
        }
        requireActivity().getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback)
    }
}

可以在https://developer.android.com/guide/navigation/navigation-custom-back上查看官方文档


1
这是最好的答案。您应该能够处理来自工具栏的后按和正常的后按。竖起大拇指
odifek

这对我很有帮助!我的工具栏后退按钮没有触发,OnBackPressedCallback但添加后可以toolbar.setNavigationOnClickListener { onBackPressed() }正常工作,因此现在硬件后退和工具栏后退工作相同。感谢您给出清晰明确的答案!
波比

这是正确且最合乎逻辑的解决方案。一定会经受住时间的考验。
Rowland Mtetezi

我只将代码用于Fragment反向覆盖,它工作正常!
sud007 '20

10

这是应该执行您想要的解决方案,但我认为这是一个糟糕的解决方案,因为它与Android导航组件的想法(让android处理导航)背道而驰。

覆盖活动中的“ onBackPressed”

override fun onBackPressed() {
    when(NavHostFragment.findNavController(nav_host_fragment).currentDestination.id) {
        R.id.fragment2-> {
            val dialog=AlertDialog.Builder(this).setMessage("Hello").setPositiveButton("Ok", DialogInterface.OnClickListener { dialogInterface, i ->
                finish()
            }).show()
        }
        else -> {
            super.onBackPressed()
        }
    }
} 

1
感谢您的解决方案,但是在决定切换到导航组件之前,我已经使用了此功能。似乎为时过早:(
Kiryl Tkach

为时过早。我实施了类似的hackey解决方案来处理appbar向上导航
filthy_wizard

9

我是这样写主要活动的

override fun onSupportNavigateUp(): Boolean {
        return findNavController(R.id.my_nav_host_fragment).navigateUp(appBarConfiguration)
    }   

6

2.1.0-alpha06

如果只想在当前片段中处理backpress

requireActivity().onBackPressedDispatcher.addCallback(this@LoginFragment) {
    // handle back event
}

对于整个活动

requireActivity().onBackPressedDispatcher.addCallback() {
    // handle back event
}

6

这是两行代码,可以侦听来自片段的回压,[TESTED and WORKING]

  requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {

            //setEnabled(false); // call this to disable listener
            //remove(); // call to remove listener
            //Toast.makeText(getContext(), "Listing for back press from this fragment", Toast.LENGTH_SHORT).show();
     }

5

聚会有点晚了,但是在导航组件1.0.0-alpha09的最新版本中,现在有了AppBarConfiguration.OnNavigateUpListener。

请参阅以下链接以获取更多信息:https : //developer.android.com/reference/androidx/navigation/ui/AppBarConfiguration.OnNavigateUpListener https://developer.android.com/jetpack/docs/release-notes


感谢您向我展示发行说明!发现android:menuCategory =“ secondary”避免了弹出堆栈!
Valentin Gavran,

对我来说,这仅适用于工具栏,而不适用于“后退”按钮
Jurij Pitulja

3

推荐的方法对我有用,但是在更新我的库后 implementation 'androidx.appcompat:appcompat:1.1.0'

实施如下

 val onBackPressedCallback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            // Handle the back button event
        }
    }
    requireActivity().onBackPressedDispatcher.addCallback(this, onBackPressedCallback)

使用Kotlin


2

您可以使用OnBackPressedDispatcher提供自定义的后退导航

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
// and if you want to need navigate up
//NavHostFragment.findNavController(this).navigateUp()
    }

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

Android官方指南中的更多说明:https : //developer.android.com/guide/navigation/navigation-custom-back


1

如果您使用导航组件,请在onCreateView()方法中遵循以下代码(在此示例中,我只想通过此片段关闭我的应用程序)

 OnBackPressedCallback backPressedCallback = new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            new AlertDialog.Builder(Objects.requireNonNull(getActivity()))
                    .setIcon(R.drawable.icon_01)
                    .setTitle(getResources().getString(R.string.close_app_title))
                    .setMessage(getResources().getString(R.string.close_app_message))
                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            getActivity().finish();
                        }
                    })
                    .setNegativeButton(R.string.no, null)
                    .show();
        }
    };
    requireActivity().getOnBackPressedDispatcher().addCallback(this, backPressedCallback);

1

如果您也希望工具栏的“后退”按钮具有相同的行为,只需将其添加到活动中即可:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        getOnBackPressedDispatcher().onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

1

只需添加这些行

     override fun onBackPressed() {
            if(navController.popBackStack().not()) {
            //Last fragment: Do your operation here 
            finish()
   } 

如果这不是您的最后一个片段,navController.popBackStack()只会弹出您的片段


0

这是我的解决方案

使用androidx.appcompat.app.AppCompatActivity了包含活性NavHostFragment片段。

定义以下接口并将其实现在所有导航目标片段中

interface InterceptionInterface {

    fun onNavigationUp(): Boolean
    fun onBackPressed(): Boolean
}

在您的活动中覆盖onSupportNavigateUponBackPressed

override fun onSupportNavigateUp(): Boolean {
        return getCurrentNavDest().onNavigationUp() || navigation_host_fragment.findNavController().navigateUp()
}

override fun onBackPressed() {
        if (!getCurrentNavDest().onBackPressed()){
            super.onBackPressed()
        }
}

private fun getCurrentNavDest(): InterceptionInterface {
        val currentFragment = navigation_host_fragment.childFragmentManager.primaryNavigationFragment as InterceptionInterface
        return currentFragment
}

该解决方案的优势在于,导航目标片段在分离后就不必担心其监听器的注销。


0

我尝试了Jurij Pitulja解决方案,但我也无法使用Kiryl Tkach的解决方案来找到getOnBackPressedDispatcher或addOnBackPressedCallback,因此无法找到当前片段,所以这是我的:

interface OnBackPressedListener {
    fun onBackPressed(): Boolean
}

override fun onBackPressed() {
    val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment)
    val currentFragment = navHostFragment?.childFragmentManager!!.fragments[0]
    if (currentFragment !is OnBackPressedListener || !(currentFragment as OnBackPressedListener).onBackPressed()) super.onBackPressed()

这样,您可以分段确定活动是否应控制后退。

另外,您对所有活动都具有BaseActivity,可以像这样实现

override fun onBackPressed() {
    val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment)
    if (navHostFragment != null){
        val currentFragment = navHostFragment.childFragmentManager.fragments[0]
        if (currentFragment !is AuthContract.OnBackPressedListener ||
                !(currentFragment as AuthContract.OnBackPressedListener).onBackPressed()) super.onBackPressed()
    } else {
        super.onBackPressed()
    }
}

0

如果您的应用程序使用BaseFragment,则可以将onBackPressedDispatcher添加到基本片段中。

//Make a BaseFragment for all your fragments
abstract class BaseFragment : Fragment() {

private lateinit var callback: OnBackPressedCallback

/**
 * SetBackButtonDispatcher in OnCreate
 */

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

/**
 * Adding BackButtonDispatcher callback to activity
 */
private fun setBackButtonDispatcher() {
    callback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            onBackPressed()
        }
    }
    requireActivity().onBackPressedDispatcher.addCallback(this, callback)
}

/**
 * Override this method into your fragment to handleBackButton
 */
  open fun onBackPressed() {
  }

}

通过扩展基本片段覆盖片段中的onBackPressed()

//How to use this into your fragment
class MyFragment() : BaseFragment(){

private lateinit var mView: View

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    mView = inflater.inflate(R.layout.fragment_my, container, false)
    return mView.rootView
}

override fun onBackPressed() {
    //Write your code here on back pressed.
}

}


0

根据您的逻辑,如果只想关闭当前片段,则必须传递viewLifecycleOwner,代码如下所示:

   requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            requireActivity().finish()
        }
    })

但是,如果您想关闭backPressed上的应用程序,无论是从哪个片段(可能您都不想要!),都不要传递viewLifecycleOwner。另外,如果要禁用后退按钮,请不要在handleOnBackPressed()内部执行任何操作,请参见下文:

 requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            // do nothing it will disable the back button
        }
    })

0

尝试这个。我认为这会对您有所帮助。

override fun onBackPressed() {
    when (mNavController.getCurrentDestination()!!.getId()) {

        R.id.loginFragment -> {
            onWarningAlertDialog(this, "Alert", "Do you want to close this application ?")
        }
        R.id.registerFragment -> {
            super.onBackPressed()
        }
    }
}



private fun onWarningAlertDialog(mainActivity: MainActivity, s: String, s1: String) {

        val dialogBuilder = AlertDialog.Builder(this)
        dialogBuilder.setMessage(/*""*/s1)
                .setCancelable(false)
                .setPositiveButton("Proceed", DialogInterface.OnClickListener { dialog, id ->
                    finish()
                })
                .setNegativeButton("Cancel", DialogInterface.OnClickListener { dialog, id ->
                    dialog.cancel()
                })

        // create dialog box
        val alert = dialogBuilder.create()
        // set title for alert dialog box
        alert.setTitle("AlertDialogExample")
        // show alert dialog
        alert.show()
    }

0

如果您正在使用片段,或将其添加到按钮单击侦听器中,请使用它。这对我有用。

requireActivity().onBackPressed()

当活动检测到用户按下返回键时调用。在调用android.app.Activity#onBackPressed()的默认行为之前,可以让getOnBackPressedDispatcher()OnBackPressedDispatcher}处理后退按钮。


0

我搜索了许多线程,但没有一个起作用。终于我找到了一个:

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar mToolbar = findViewById(R.id.topAppBar);
    setSupportActionBar(mToolbar);
}

@Override
public boolean onSupportNavigateUp() {
    navController.navigateUp();
    return super.onSupportNavigateUp();
}

MyFragment.java

@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    Toolbar mToolbar = (MainActivity) getActivity().findViewById(R.id.topAppBar);
    mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Do something when uses presses back button (showing modals, messages,...)
            // Note that this will override behaviour of back button
        }
    });
}

@Override
public void onStop() {
    // Reset back button to default behaviour when we leave this fragment
    Toolbar mToolbar = (MainActivity) getActivity().findViewById(R.id.topAppBar);
    mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mainActivity.onBackPressed();
        }
    });

    super.onStop();
}

0

只需为片段创建扩展功能

fun Fragment.onBackPressedAction(action: () -> Boolean) {
    requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object :
        OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            this.isEnabled = action()
            if (!this.isEnabled) {
                requireActivity().onBackPressed()
            }
        }
    })
}

然后在片段中将代码放入onCreateView中(操作必须返回false才能调用活动onBackPressed)

onBackPressedAction { //do something }

0

我需要同时支持真实的后退按钮和工具栏的后退按钮,并且在两种情况下都可以覆盖“后退”单击(以显示对话框或其他内容)。我在活动和片段中的相应布尔检查(在本例中为“ onBackPressed”)中做了一个附加方法:

// Process hardware Back button
override fun onBackPressed() {
    if (canCloseActivity()) {
        super.onBackPressed()
    }
}

// Process toobar Back and Menu button
override fun onSupportNavigateUp(): Boolean {
    if (canCloseActivity()) {
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }
    return false
}

// Do real check if has unfinished tasks, return false to override activity closing
private fun canCloseActivity(): Boolean {
    val currentFragment = navHostFragment.childFragmentManager.primaryNavigationFragment

    return when {
        currentFragment is MyFragment && currentFragment.onBackPressed() -> false

        drawerLayout.isOpen -> {
            drawerLayout.close()
            false
        }
        fullScreenPreviewLayout.visibility == View.VISIBLE -> {
            closeFullscreenPreview()
            false
        }
        else -> true
    }
}

-1

我的意见requireActivity()。onBackPressed()

requireActivity().onBackPressed()
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.