2016-09-11 29 views
1

我是Android的初学者,并试图开发一个Android应用程序,其中我卡在后面的导航中。我的问题是: 如何管理带有活动和片段的后台堆栈。在Android中的后退导航

与frag1 A1的活动需要A2的活性和A2的活性显示在其中一个列表中点击一个用户列表检查用户的个人资料,与破片2

来电A1活动在A1的活动Frag2的开放,我们使用意图的标志:flag_activity_reorder_to_front并添加frag1与FragmentManager交易到堆栈中现在

如果我点击在当时它显示frag1代替A2活性A1活动。

如果我没有将frag1添加到backstack中,然后返回,它可以在第一次返回时使用,但是在第二次返回时它会退出应用程序。

有什么建议吗?

回答

0

尝试使用单个活动并使用接口处理其中的所有片段事务。活动应该实现这个接口。 例子:

public interface FragChanger { 
    int NEXT_FRAGHELLO =1; 
    int NEXT_FRAGSET = 2; 
    int NEXT_FRAGSELECT =3; 
    int NEXT_FRAGLOG=4; 
    int NEXT_FRAGCHAT=5; 

    void onFragmentChange(int nextFrag); 


} 

下应该是在你的活动:

@Override 
    public void onFragmentChange(int nextFrag) { 

     FragmentManager fm = getSupportFragmentManager(); 
     FragmentTransaction ft = fm.beginTransaction(); 


     switch (nextFrag){ 
      case NEXT_FRAGHELLO: 

       break; 
      case NEXT_FRAGSET: 
       FragSet fragSet = new FragSet(); 

       ft.replace(containerId,fragSet,"fragset"); 
       ft.addToBackStack(null); 
       ft.commit(); 

       break; 
      case NEXT_FRAGSELECT: 
       FragSelect fragSelect = new FragSelect(); 

       ft.replace(containerId,fragSelect,"fragselect"); 
       ft.addToBackStack(null); 
       ft.commit(); 
       break; 
      case NEXT_FRAGCHAT: 
       FragChat fragChat = new FragChat(); 
       ft.replace(containerId,fragChat,"fragchat"); 
       ft.addToBackStack(null); 
       ft.commit();} 
       break; 

      case NEXT_FRAGLOG: 

       ft.replace(containerId,fragLog,"fraglog"); 
       ft.addToBackStack(null); 
       ft.commit(); 
       break; 
} 

处理回到你的活动:

@Override 
    public void onBackPressed() { 
     Log.d(TAG,"button back pressed"); 
     //Check which fragment is displayed an do whatever you need 
     //for example like this 
if (getSupportFragmentManager().findFragmentById(containerId) instanceof FragLog){ 
     Fragment fl = getSupportFragmentManager().findFragmentByTag("fraglog"); 
     if (fl !=null){ 
      FragmentManager fm = getSupportFragmentManager(); 
      FragmentTransaction ft = fm.beginTransaction(); 

      ft.remove(fl); 
      ft.commit(); 
      return; 
     } 
     } 


    } 

当然,这只是一个例子,但也可以是在你的情况下有用