这个问题涉及 Xamarin Android 和使用 C#,但我认为使用 Android Studio 的 Java 开发人员......仍然可以理解问题并可能有所帮助。
正如我在网上研究的那样,一切都应该很简单。这里的问题是 Toolbar
(在 v7 支持库中)按预期显示在顶部,但 Home 按钮没有按我想要的显示。
我在主布局中有一个 DrawerLayout
,单击主页按钮应该展开抽屉布局,同时主页图标应该切换到左箭头图标(后退图标)。
单击后退按钮应折叠抽屉布局并将图标切换回主页的初始图标。
我现在拥有的是主页按钮始终显示向左箭头图标。我想那是因为我使用了调用 SupportActionBar.SetDisplayHomeAsUpEnabled(true);
但是如果没有那样设置,则不会显示任何内容,因此无法单击。
下面是生成主页按钮的代码,但它的图标始终显示向左箭头:
工具栏布局:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="@+id/mainToolbar"
android:background="?attr/colorPrimary"
android:layout_height="@dimen/ToolbarHeight">
</android.support.v7.widget.Toolbar>
背后的代码:
//here is in OnCreate callback of the main Activity
var toolBar = FindViewById<Toolbar>(Resource.Id.mainToolbar);
SetSupportActionBar(toolBar);
SupportActionBar.SetDisplayShowHomeEnabled(true);
SupportActionBar.SetDisplayHomeAsUpEnabled(true);
SupportActionBar.SetHomeButtonEnabled(true);
使用上面的代码,如果我注释掉 SupportActionBar.SetDisplayHomeAsUpEnabled(true);
行,则不会显示任何内容(虽然我想要一些图标,例如
要显示的应用程序图标)。
我希望这里有人能弄清楚我在这里错过了什么。 顺便说一句,我在 Android 4.4.4 上运行代码,虽然我认为这不是 Android 版本的问题(因为支持库应该在这种情况下工作)。
更新: 主要布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootFrame"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<android.support.v4.widget.DrawerLayout
android:id="@+id/main"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<!-- main content -->
<LinearLayout
android:id="@+id/mainContent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<include layout="@layout/MainToolBar"/>
<FrameLayout android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:id="@+id/contentFrame"></FrameLayout>
</LinearLayout>
<!-- left menu -->
<android.support.design.widget.NavigationView
android:layout_height="fill_parent"
android:layout_width="wrap_content"
android:minWidth="@dimen/LeftMenuMinWidth"
android:layout_gravity="start"
android:fitsSystemWindows="false"
android:background="@color/LeftMenuBackgroundColor"
android:id="@+id/leftMenu">
<!-- layout for the menu here ... -->
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
设置抽屉监听器的代码,这是我在上面发布的设置工具栏的代码之后放置的:
var dl = FindViewById<DrawerLayout>(Resource.Id.main);
//the ActionBarDrawerToggle here is from Android.Support.V7.app
dl.AddDrawerListener(new ActionBarDrawerToggle(this, dl, toolBar, 0, 0));
我希望现在我已经提供了足够的代码。
最佳答案
当使用 ActionBarDrawerToggle
时,您需要在初始化后对其调用 SyncState()
以使其在导航按钮上实际设置自己的图标。
还建议在 Activity
的 OnPostCreate()
方法中执行此操作,这样它可以正确同步,例如,如果抽屉在设备期间打开旋转。
关于android - 新工具栏的 AppCompatActivity 没有正确显示主页按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39502309/