BottomAppBar не загружается должным образом

Я пытаюсь воспроизвести этот нижний AppBar

Но независимо от того, какому руководству я следую, лучшее, что я могу получить, это это.

Я полный новичок в разработке Android, и это сводило меня с ума. Я проверил созданные новые проекты, чтобы узнать, была ли проблема с моей. Я старательно скопировал каждую зависимость Gradle, которая могла бы иметь отношение, из разных руководств, но, похоже, ничего не работает.

Автозаполнение редактора распознает представление BottomAppBar и его атрибуты, но в превью вообще не работает, а в приложении просто вылетает.

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'


android {
    compileSdkVersion 29
    buildToolsVersion "29.0.0"
    defaultConfig {
        applicationId "com.hlag.projecttabletop"
        minSdkVersion 25
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

    implementation 'com.google.android.material:material:1.1.0-alpha08'
    testImplementation 'junit:junit:4.12'

}

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout
        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"
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"
        android:orientation = "vertical"
        tools:context = ".activities.TestActivity">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width = "match_parent"
            android:layout_height = "match_parent">

        <com.google.android.material.bottomappbar.BottomAppBar
                android:layout_width = "match_parent"
                android:layout_height = "wrap_content"
                style = "@style/Widget.MaterialComponents.BottomAppBar"
                android:layout_gravity = "bottom"
                android:id = "@+id/bottomAppBar"
                android:backgroundTint = "@color/colorPrimary"
                app:navigationIcon = "@drawable/ic_drag_handle_black_24dp">
        </com.google.android.material.bottomappbar.BottomAppBar>

        <com.google.android.material.floatingactionbutton.FloatingActionButton
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                app:fabSize = "normal"
                app:layout_anchor = "@id/bottomAppBar"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</LinearLayout>

Покажи свои стили.xml

Sony 20.07.2019 22:57
0
1
2 856
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Тема вашего приложения должна расширять тему MaterialComponents, а не AppCompatTheme,

так.

<style name = "AppTheme" parent = "Theme.MaterialComponents.DayNight.NoActionBar">

BottomAppBar следует завернуть в CoordinatorLayout

и вам не хватает app:fabAlignmentMode для нижней панели приложений

Удачного кодирования... :-)

Sony 21.07.2019 01:30

Просто заметка. app:fabAlignmentMode имеет значение по умолчанию FAB_ALIGNMENT_MODE_CENTER.

Gabriele Mariotti 26.08.2019 22:00

Я предлагаю вам сделать это следующим образом:

стиль.xml :

    <style name = "AppTheme" parent = "Theme.MaterialComponents.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>

Activity_test.xml :

<?xml version = "1.0" encoding = "utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    android:id = "@+id/coordinator"
    xmlns:app = "http://schemas.android.com/apk/res-auto"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".TestActivity">

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id = "@+id/app_bar"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:layout_gravity = "bottom"
        android:backgroundTint = "@color/colorPrimary"
        app:navigationIcon = "@drawable/ic_drag_handle_black_24dp"
        style = "@style/Widget.MaterialComponents.BottomAppBar"/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id = "@+id/button_add_note"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        app:layout_anchor = "@id/app_bar"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Примечание : Ваш родительский макет должен быть CoordinatorLayout

Это должно работать

Если вы используете MaterialTheme, нет необходимости устанавливать style = "@style/Widget.MaterialComponents.BottomAppBar", так как это стиль по умолчанию для BottomAppBar

Gabriele Mariotti 26.08.2019 22:02

Другие вопросы по теме