我的应用程序有几个活动。对于所有这些工具条,工具栏都是从主活动中隐式继承的。我只想为单个活动()设置一个特定的工具栏,但对于所有其他活动,我想继续从主活动继承它们。。
如果我试图为我的单个活动设置一个新工具栏-我得到了一个众所周知的异常This Activity already has an action bar ,但是为了修复它,我可以添加到我的AppTheme样式:
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>我可以设置不同的工具栏,
但是问题是:在这种情况下,对于每个活动,我需要显式地设置一个工具栏,但是我想从主工具栏继承一个工具栏。
请在下面找到一些代码:
我的主工具栏
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/AppTheme.PopupOverlay" android:layout_weight="1">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>和风格:
<style name="AppTheme" parent="Theme.AppCompat.Light">
<!-- Customize your theme here. -->
<item name="colorPrimary">@android:color/white</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Light"/>
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>以及manifest.xml的主要活动
<activity
android:name=".."
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
..
</intent-filter>
</activity>和MainActivity onCreate方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
...
} 发布于 2022-01-04 12:15:55
要共享一个工具栏,最好的方法是将工具栏布局提取到一个单独的布局文件中,例如app_bar.xml,然后将它包含在您想要在下面一行中使用的每个活动中:
<include layout="@layout/app_bar"/>然后,在您需要定制应用程序栏的活动中,您只是不使用这个应用程序栏,而是使用一个新定制的应用程序栏。
假设应用程序栏共享了很多定制功能,并且您不想重复。在这种情况下,您可以为应用程序栏创建自定义主题并为工具栏设置此主题,在另一个主题中扩展此主题,覆盖要更改的属性,并为特定用例设置扩展主题。
https://stackoverflow.com/questions/70578036
复制相似问题