2016-03-26 70 views
1

我的应用程序中只有一个活动,其中包含导航视图以浏览3个片段。Actionbar Up Button Listener

当我浏览到一个片段,我得到了汉堡包菜单图标改为了按钮,在onNavigationItemSelected方法是这样的:

actionBarDrawerToggle.setDrawerIndicatorEnabled(false); 
getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

向上按钮显示良好,但没有效果呢。

我想单击按钮时导航到堆栈中的前一个片段,但无法将侦听器添加到该按钮。

我已经尝试使用:

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

    return super.onOptionsItemSelected(item); 
} 

但这不会被调用。我认为它没有被调用,因为我在清单中没有父项活动。

在此先感谢。

回答

0

你不应该调用onBackPressed,你应该使用片段事务方法来进行片段之间的事务处理,就像我使用replace方法将当前片段替换为之前的片段。容器是包含片段的布局。

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
transaction.replace(R.id.fragment_container, newFragment); 
    transaction.commit(); 

我希望它给你一些方向。

if (id == android.R.id.home) { 
    //put the code like above here. 
    return true; 
} 
+0

这不是我的问题..我知道如何浏览片段,但我应该在哪里放这段代码?我的意思是没有听众或在操作栏 –

+0

中的向上按钮我现在编辑了答案。其实android.R.id.home对应于你所关心的按钮。 – Ruag

+0

我试过了,onOptionsItemSelected从来不叫 –