Я впервые учусь реализовывать пользовательские темы для Android, я не очень понимаю свой styles.xml код. Я хочу установить тему во время выполнения в соответствии с выбором темы пользователем. Если я не включу Toolbar, я не знаю, как установить Toggle и принудительно NavigationView поверх ActionBar. Приложение не открывается и вылетает со следующим error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kotlinappv3/com.example.kotlinappv3.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2928)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3063)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6729)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at androidx.appcompat.app.AppCompatDelegateImpl.setSupportActionBar(AppCompatDelegateImpl.java:345)
at androidx.appcompat.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.example.kotlinappv3.MainActivity.onCreate(MainActivity.kt:35)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2908)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3063)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6729)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Это мой styles.xml файл:
<style name = "MyLightTheme" parent = "Theme.AppCompat.Light"/>
<style name = "NoActionBar" parent = "MyLightTheme">
<item name = "windowActionBar">false</item>
<item name = "windowNoTitle">true</item>
<item name = "windowActionBarOverlay">true</item>
</style>
<style name = "MyLightTheme.Red">
<item name = "colorPrimary">@color/red_4_100</item>
<item name = "colorPrimaryDark">@color/red_6_100</item>
<item name = "colorAccent">@color/red_6_100</item>
</style>
<!-- Some more colors ...
<style name = "MyLightTheme.ColorName"> -->
Это файл AndroidManifest.xml:
<activity
android:name = ".MainActivity"
android:theme = "@style/NoActionBar">
Это файл activity_main.xml:
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:id = "@+id/drawer_layout"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:fitsSystemWindows = "true"
tools:openDrawer = "start" >
<LinearLayout
android:orientation = "vertical"
android:layout_width = "match_parent"
android:layout_height = "match_parent" >
<include layout = "@layout/toolbar"/>
<FrameLayout
android:id = "@+id/fragment_main"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
<include layout = "@layout/navigation_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
А это из MainActivity.kt класса:
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(MyThemes(this).getMyThemeId()) // setTheme(R.style.MyLightTheme_Red)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) { supportFragmentManager.beginTransaction().replace(R.id.fragment_main, MyFragment()).commit() }
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
val toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
val navView: NavigationView = findViewById(R.id.nav_view)
navView.setNavigationItemSelectedListener(this)
}
измени свой стиль на NoActionBar с этим
<style name = "MyLightTheme.NoActionBar" parent = "Theme.AppCompat.Light.NoActionBar">
...
</style>
и не надо добавлять
<item name = "windowActionBar">false</item>
<item name = "windowNoTitle">true</item>
и в Manifest.xml
<activity
android:name = ".MainActivity"
android:theme = "@style/MyLightTheme.NoActionBar">
Вы уверены, что изменили тему в манифесте активности?
Я не меняю тему в манифесте активности, я меняю ее в основном методе oncreate активности
setTheme(MyThemes(this).getMyThemeId()) // setTheme(R.style.MyLightTheme_Red)
Вы сами сказали, что устанавливаете тему на MyLightTheme_Red:
<style name = "MyLightTheme.Red">
<item name = "colorPrimary">@color/red_4_100</item>
<item name = "colorPrimaryDark">@color/red_6_100</item>
<item name = "colorAccent">@color/red_6_100</item>
</style>
Это НЕ исключает панель инструментов, поскольку у нее нет родителя. Просто добавь
<style name = "MyLightTheme.Red" parent = "NoActionBar">
И теперь он унаследует свойства «Нет панели инструментов» этого стиля.
Спасибо за ответ, я также нашел пример на гитхаб
Для AndroidX используйте эту тему в своем res/values/styles.xml:
<style name = "MyLightTheme.NoActionBar" parent = "Theme.MaterialComponents.Light.NoActionBar">
...
</style>
Добавьте эту тему в свой AndroidManifest.xml:
<activity
android:name = ".MainActivity"
android:theme = "@style/MyLightTheme.NoActionBar">
Таким образом, я получаю панель инструментов под панелью действий, и я не знаю, как установить переключатель на панели действий.