Панель инструментов Android: маленький текст заголовка в ландшафтном режиме
Я тестирую новую панель инструментов и тему AppCompat на Android и столкнулся с проблемой. Текст заголовка панели инструментов выглядит нормальным в портретном режиме, но в ландшафтном режиме он стал довольно небольшим, хотя я не делал ничего в коде, чтобы изменить размер текста заголовка. Вот скриншоты:
![Portrait]()
![Landscape]()
activity_main.xml:
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.techfunmyanmar.jujaka.ui.MainActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment
android:id="@+id/navigation_drawer"
android:name="com.techfunmyanmar.jujaka.ui.NavigationDrawerFragment"
android:layout_width="@dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="@layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
styles.xml:
<resources>
<!-- Base application theme. -->
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primary_dark</item>
<item name="colorAccent">@color/accent</item>
</style>
<!-- Main application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
</style>
</resources>
Ответы
Ответ 1
Я попытался установить android:titleTextAppearance
на панели инструментов, но стиль не применялся. Затем я понял, что использую тему AppCompat, поэтому использовал app:titleTextAppearance
, и теперь стиль применяется. Похоже, что маленькие буквы в ландшафте - это проблема во встроенном стиле AppCompat.Toolbar.Title
, поэтому я переделал его, чтобы установить размер шрифта вручную. Окончательный код:
Панель инструментов XML:
<android.support.v7.widget.Toolbar
android:id="@+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:titleTextAppearance="@style/ToolbarTitle"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
Стиль панели инструментов:
<style name="ToolbarTitle" parent="@style/TextAppearance.Widget.AppCompat.Toolbar.Title">
<item name="android:textSize">20sp</item>
</style>
Ответ 2
AOSP Issue # 170707 написано относительно изменения размера текста для заголовка и субтитров. Ответ участника проекта был "Работает по назначению". Идентично для поведения структуры. " Хотя я не считаю изменение размера текста желательным поведением по умолчанию, это звучит так, как инженеры AppCompat должны были поддерживать согласованность с (ошибочным) отношением к структуре. Затем разработчикам остается переопределить стили по умолчанию, как описано в ответе Chilly Chan.
Дополнение к Chilly Chan отвечает:
1) Размер текста субтитров можно контролировать аналогичным образом, определяя другой стиль, полученный из TextAppearance.Widget.AppCompat.Toolbar.Subtitle.
2) Значения по умолчанию для размера заголовка/субтитров в портретной ориентации 20dp/16dp (на моей Galaxy S3, 4.4.2.). Пример Chilly Chan указывает "17sp". Используйте "sp", только если вы хотите, чтобы настройка предпочтений пользователя влияла на размер заголовка/субтитров.
Ответ 3
Попробуйте добавить это в свою панель инструментов под свойством activity_main.xml.
Android: MinHeight = "андроид: атр /actionBarSize "
Я также заметил, что вы используете стандартную панель темных действий, предлагаете использовать Theme без панели действий, определить новую панель инструментов, где
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
<android.support.v7.widget.Toolbar
android:id="@+id/my_awesome_toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary" />
Ответ 4
Я искал решение без специальной панели инструментов, но с пользовательским стилем, и этот код помогло:
styles.xml
<style name="MyTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="actionBarStyle">@style/MyActionBar</item>
</style>
<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid">
<item name="titleTextStyle">@style/MyTitleTextStyle</item>
</style>
<style name="MyTitleTextStyle" parent="@style/TextAppearance.AppCompat.Title">
<item name="android:textSize">20sp</item> <!-- Default for portrait is 20sp and for landscape 14sp-->
</style>
AndroidManifest.xml
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/MyTheme"/>
Где MainActivity расширяет AppCompatActivity; испытаны на API 19, 22 и 23.
Ответ 5
Я думаю, что это связано с некоторыми изменениями макета, которые выполняются при повороте устройства, поскольку похоже, что вы можете предотвратить изменение размера, добавив что-то вроде
android:configChanges="orientation|screenSize"
в AndroidManifest.xml для действия, в котором вы находитесь. Как всегда, android: configChanges имеет больше последствий, поэтому его следует использовать, только если вам это действительно нужно:)