Search code examples
androidkotlinandroid-actionbar

Display action bar in few activities


I created a custom theme style with no action bar:

<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>

And in my manifest I use this 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">

That way there is no action bar in all of my activites. However I would like it to appear in just certain activities. I tried to add the code:

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()

But the action bar is not showing and I assume the reason is that the theme doesn't support an action bar. I would only like to display the action bar in few activities, even so should I create a theme with an action bar and hide it programatically in most of the activities?


Solution

  • Create style with action bar

    <!-- 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>
    

    then create another style with no action bar

    <style name="AppTheme.NoActionBar">
            <item name="windowActionBar">false</item>
            <item name="windowNoTitle">true</item>
        </style>
    

    then use like this

    activities with action bar

    <activity android:name=".MyActivity"
                android:theme="@style/AppTheme"
                android:label="MyActivity"></activity>
    

    activities with no action bar

    <activity android:name=".MyActivity"
                android:theme="@style/AppTheme.NoActionBar"
                android:label="MyActivity"></activity>