Android Fragment 手柄返回按钮按下 [英] Android Fragment handle back button press

查看:37
本文介绍了Android Fragment 手柄返回按钮按下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的活动中有一些片段

[1], [2], [3], [4], [5], [6]

如果当前活动片段为 [2],则在返回按钮上按 I 必须从 [2] 返回到 [1],否则不执行任何操作.

And on Back Button Press I must to return from [2] to [1] if current active fragment is [2], or do nothing otherwise.

这样做的最佳做法是什么?

What is the best practise to do that?

编辑:应用程序不得从 [3]...[6] 返回到 [2]

EDIT: Application must not return to [2] from [3]...[6]

推荐答案

当你在 Fragment 之间转换时,调用 addToBackStack() 作为你的 FragmentTransaction 的一部分:

When you are transitioning between Fragments, call addToBackStack() as part of your FragmentTransaction:

FragmentTransaction tx = fragmentManager.beginTransation();
tx.replace( R.id.fragment, new MyFragment() ).addToBackStack( "tag" ).commit();

如果您需要更详细的控制(即当某些 Fragment 可见时,您想取消后退键)您可以在您的 Fragment 的父视图上设置一个 OnKeyListener:

If you require more detailed control (i.e. when some Fragments are visible, you want to suppress the back key) you can set an OnKeyListener on the parent view of your fragment:

//You need to add the following line for this solution to work; thanks skayred
fragment.getView().setFocusableInTouchMode(true);
fragment.getView().requestFocus();
fragment.getView().setOnKeyListener( new OnKeyListener()
{
    @Override
    public boolean onKey( View v, int keyCode, KeyEvent event )
    {
        if( keyCode == KeyEvent.KEYCODE_BACK )
        {
            return true;
        }
        return false;
    }
} );

这篇关于Android Fragment 手柄返回按钮按下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆