0
我知道有很多像這樣回答的問題,但沒有發現任何作品。Android工具欄導航後退按鈕回調從未呼籲
我有一個活動(MainActivity
),負責顯示不同的片段。另外,在活動中,我有導航抽屜,只顯示在一個片段上(它隱藏在其他片段上)。
問題是,工具欄導航回調從不稱爲。後退按鈕顯示,但點擊它不做任何事。此外(我不知道它是否有任何區別),但用戶從另一個片段獲取片段,在這個片段中,除了導航後退按鈕被隱藏之外,我做了與本例中相同的事情。
XML的活動是這樣的:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="@+id/main_toolbar"
layout="@layout/toolbar"/>
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/activity_main_drawer"/>
</android.support.v4.widget.DrawerLayout>
包括工具欄:現在
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
app:theme="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"/>
,在活動我安裝一個工具欄,並把監聽器的後退按鈕:
setSupportActionBar(mainToolbar);
setTitle(getResources().getString("Some title"));
mainToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
在我需要後退按鈕的特定片段中,我會這樣做以顯示它:
if (this.context.getSupportActionBar() != null) {
this.context.getSupportActionBar().setTitle("Fragment title"));
this.context.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.context.getSupportActionBar().setDisplayShowHomeEnabled(true);
}
而且,因爲我不希望使用導航抽屜/顯示,在該片段中我稱之爲在活動中定義的方法,執行該代碼:
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
drawerToggle.setDrawerIndicatorEnabled(false);
我將該片段添加到後臺堆已經。另外,爲什麼我應該做同樣的事情兩次?先在'onCreate'然後在'onBackStackChanged'中?而且,每次疊加變化 –
我寫的操作是兩次。你只能將該代碼放在BackStackChange Listener –
中,如果你有2個片段,並且你想在第二個片段顯示時返回按鈕啓用,那麼你可以檢查是否存在第二個片段的對象,然後將它添加到後端堆棧 –