2016-03-26 71 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從來不叫 –