Android的碎片处理后退按钮preSS [英] Android Fragment handle back button press
问题描述
我有一些片段在我的活动
I have some fragments in my activity
[1], [2], [3], [4], [5], [6]
和上后退按钮preSS我必须从返回[2] [1],如果当前的活动片段[2],或者什么也不做,否则。
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?
修改:应用程序不能返回[2] [3] ... [6]
EDIT: Application must not return to [2] from [3]...[6]
推荐答案
当您在片段之间的转换,呼叫 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();
如果您需要更详细的控制(即当一些片段可见,要想喝preSS返回键),你可以在父设置 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的碎片处理后退按钮preSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!