我创建了没有操作栏的自定义主题样式:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
在清单中,我使用这种样式:
<application
android:largeHeap="true"
android:name="androidx.multidex.MultiDexApplication"
android:allowBackup="true"
android:icon="@drawable/icon"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
这样,我所有的活动都没有操作栏。但是,我希望它仅出现在某些活动中。我试图添加代码:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val layoutInflater: LayoutInflater = LayoutInflater.from(this)
val view: View = layoutInflater.inflate(R.layout.activity_edit_profile, null)
setContentView(view)
supportActionBar?.show()
但是操作栏未显示,我认为原因是主题不支持操作栏。我只想在很少的活动中显示动作栏,即使如此,我是否应该创建带有动作栏的主题并以编程方式将其隐藏在大多数活动中?
使用操作栏创建样式
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</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>
然后像这样使用
带操作栏的活动
<activity android:name=".MyActivity"
android:theme="@style/AppTheme"
android:label="MyActivity"></activity>
没有动作栏的活动
<activity android:name=".MyActivity"
android:theme="@style/AppTheme.NoActionBar"
android:label="MyActivity"></activity>
使用ActionBar
创建主题
<style name="AppActionBarTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
您已经有主题AppTheme
,没有任何操作栏。
像这样将此主题添加到Manifest
文件中的活动中
对于NoActionBar
<activity android:name=".NoActionBarActivity"
android:theme="@style/AppTheme"
android:label="NoActionBarActivity"></activity>
对于ActionBar
<activity android:name=".ActionBarActivity"
android:theme="@style/AppActionBarTheme"
android:label="ActionBarActivity"></activity>
对于整个应用程序。只需在应用程序标签中添加android:theme="@style/AppTheme"
行。就像这样
<application
android:theme="@style/AppTheme"/>
或者像这样以编程方式隐藏/显示ActionBar
//to show ActionBar
supportActionBar?.show()
//to hide ActionBar
supportActionBar?.hide()