Як додати нову кнопку "Плаваюча дія" між двома віджетами / макетами


287

Я думаю, ви бачили нові правила дизайну Android, з новою "Плаваючою кнопкою дій", яка називається "FAB"

Наприклад, ця рожева кнопка:

введіть тут опис зображення

Моє запитання звучить нерозумно, і я вже багато чого спробував, але який найкращий спосіб поставити цю кнопку на перетині двох макетів?

У наведеному вище прикладі ця кнопка ідеально розміщена між тим, що ми можемо уявити як ImageView та RelaLayout.

Я вже спробував чимало налаштувань, але переконаний, що є правильний спосіб це зробити.


Ви можете розташувати макети всередині макета та розмістити кнопку на цій макеті
— Chrome Penguin Studios

1
Я думаю, що ця бібліотека може дуже допомогти: github.com/ksoichiro/Android-ObservableScrollView
— андроїд розробник

Як приховати це під час прокрутки? Я зіткнувся з проблемою, коли, якщо я прокручую сторінку, файл залишається зверху і не ховається! Будь ласка, допоможіть
— Аніш Кумар

Відповіді:


473

Найкраща практика:

  • Додати compile 'com.android.support:design:25.0.1'у файл gradle
  • Використовуйте CoordinatorLayout як кореневий вигляд.
  • Додайте layout_anchor до FAB та встановіть його на вид зверху
  • Додайте layout_anchorGravityдо FAB і встановіть його на:bottom|right|end

введіть тут опис зображення

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/viewA"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.6"
            android:background="@android:color/holo_purple"
            android:orientation="horizontal"/>

        <LinearLayout
            android:id="@+id/viewB"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.4"
            android:background="@android:color/holo_orange_light"
            android:orientation="horizontal"/>

    </LinearLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:clickable="true"
        android:src="@drawable/ic_done"
        app:layout_anchor="@id/viewA"
        app:layout_anchorGravity="bottom|right|end"/>

</android.support.design.widget.CoordinatorLayout>

3
@Aprendiz Я також хотів би цитати, але я можу зрозуміти, чому це краща відповідь, ніж відповіді HughJeffner. Мені здається, це простіше, гнучкіше, менше хакі. Ви не жорстко кодуєте будь-які значення layout_height або margin, які можуть змінюватися в часі або визначатися динамічно. Відповідь Х'ю може працювати в деяких простих випадках, і , можливо , може бути обхідний шлях для деяких сторонніх бібліотек , які в повному обсязі підтримують CoordinatorLayoutі layout_anchorта layout_anchorGravityособливості, як та , яку він використовує, futuresimples .
— acrespo

1
Btw futuresimples є ДИВОВИЖНОЮ бібліотекою, а в разі , якщо хто - то цікаво є розвилка , які поєднують цей CoordinatorLayoutпідхід з цією бібліотекою, зовнішнім виглядом . А також є вилка для старих версій.
— acrespo

2
Я шукав саме ЦЕ. +1 для простоти.
— Еміліано Де Сантіс

29
Чому все це не є в документації на Android?
— Мостафа

3
за допомогою програми: layout_anchor викликає у мене проблему візуалізації (параметри linearlayout layout не можуть бути передані координаторам. :(
— DAVIDBALAS1

91

Здається, що найчистішим способом у цьому прикладі є:

  • Використовуйте відносний макет
  • Розташуйте 2 сусідні види один біля іншого
  • Вирівняйте FAB до батьківського права / кінця та додайте право / кінцеве поле
  • Вирівняйте FAB у нижній частині подання заголовка та додайте від'ємну маржу, наполовину менше розміру FAB, включаючи тінь

Приклад, адаптований під час впровадження шаманленду, використовуйте будь-який FAB, який ви хочете. Припустимо, високий FAB має 64dp, включаючи тінь:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <View
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="120dp"
    />

    <View
        android:id="@+id/body"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/header"
    />

    <fully.qualified.name.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignBottom="@id/header"
        android:layout_marginBottom="-32dp"
        android:layout_marginRight="20dp"
    />

</RelativeLayout>

Приклад макета FAB


Цей макет зробив для мене хитрість! Я використовую FABпо futuresimple - це досить просто , щоб додати і використовувати, насолоджуйтеся!
— Роман

Як ви сказали: "Розташуйте 2 сусідні погляди один під іншим" -> це була проблема, яку я отримав, я просто помітив, що мій "макет контейнера" ​​був зіпсований, не збігаючись дужками: D Спасибі: P
— Мартін Пфефер

Це не гарне рішення. Від'ємний запас, здається, усуває нижню половину сенсорної цілі кнопки. Кліки не реєструються, якщо я натискаю нижню половину файлу.
— Доронц

1
@Doronz Хм, я, здається, не маю такої проблеми. Чи правильний ваш погляд, тобто FAB - це верхній шар?
— Х'ю Джеффнер

23
android: layout_marginBottom = "- 32dp" Значення жорсткого коду з кнопкою wrap_content - це погане рішення
— Lester

51

Ви можете імпортувати зразок проекту Google в Android Studio, натиснувши Файл> Імпортувати зразок ...

Зразок імпорту

Цей зразок містить FloatingActionButton View, який успадковується від FrameLayout.

Редагувати Нову бібліотеку підтримки підтримки ви можете реалізувати як у цьому прикладі: https://github.com/chrisbanes/cheesesquare


1
Ви повинні мати Android-21 для його запуску.
— Юлія Ашомок

Ви повинні використовувати бібліотеку дизайну підтримки, якщо ви хочете використовувати FloatingActionButton. Дивіться сирний круг Google.
— Roel

16

За допомогою AppCompat 22 FAB підтримується для старих пристроїв.

Додайте нову бібліотеку підтримки у свій build.gradle (додаток):

compile 'com.android.support:design:22.2.0'

Тоді ви можете використовувати його у своєму xml:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:src="@android:drawable/ic_menu_more"
    app:elevation="6dp"
    app:pressedTranslationZ="12dp" />

Для використання elevationта pressedTranslationZвластивостей appпотрібен простір імен , тому додайте цей простір імен у свій макет: xmlns:app="http://schemas.android.com/apk/res-auto"


3
додати інформацію про appпростір імен
— Lukasz 'Severiaan' Grela

14

Зараз це частина офіційної бібліотеки підтримки дизайну.

У вашому градусі:

compile 'com.android.support:design:22.2.0'

http://developer.android.com/reference/android/support/design/widget/FloatingActionButton.html


5
Ваша відповідь трохи незрозумілий і розпливчастий, чи можете ви далі пояснити, що є частиною DSL і, можливо, процитувати відповідну інформацію на цій сторінці.
— SuperBiasedMan

Вибачте, я бачив багато посилань на зовнішні бібліотеки, тому хотів вказати на офіційну бібліотеку. Бібліотека може створити лише кнопку, але позиціонування призначене для розробників. Тож моя посада не дуже актуальна, вибачте.
— Веронні

12

Спробуйте цю бібліотеку ( тут знаходиться javadoc ), рівень хв API становить 7:

dependencies {
    compile 'com.shamanland:fab:0.0.8'
}

Він надає єдиний віджет із можливістю налаштування його через Тему, XML або Java-код.

світла між

Це дуже просто у використанні. Є доступні normalта miniреалізовані згідно з шаблоном рекламованих дій .

<com.shamanland.fab.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_action_my"
    app:floatingActionButtonColor="@color/my_fab_color"
    app:floatingActionButtonSize="mini"
    />

Спробуйте скласти демонстраційний додаток . Існує вичерпний приклад: світлі і темні теми, використовуючи з ListView, сполучаться між двома міркуваннями .


3
Просто для додання цієї відповіді ^ Ви також можете використовувати інші доступні резервні бібліотеки, такі як: github.com/FaizMalkani/FloatingActionButton та github.com/makovkastar/FloatingActionButton . І те, і інше може мати більшу підтримку. Але просто дотримуйтесь подання деталей з джерела, зазначеного в цій відповіді. Чудово працює.
— Джон Шеллі

це офіційна бібліотека?
— Кокоріко

офіційної бібліотеки немає. це моя ліб з відкритими джерелами.
— Олексій К.

Ця плаваюча кнопка дії - поганий приклад того, як її реалізувати. Це не відповідає справжнім рекомендаціям щодо дизайну матеріалів.
— Майкл

@Mike Milla, що не так з цією лібкою? які вимоги не задовольняються?
— Олексій К.

9

Ось одна додаткова безкоштовна бібліотека з плаваючою кнопкою дій для Android . Він має багато налаштувань і вимагає SDK версії 9 та новішої версії

введіть тут опис зображення

Повне демонстраційне відео

dependencies {
    compile 'com.scalified:fab:1.1.2'
}

3
Питання не в тому, як ви використовуєте FAB , а в тому, як розташувати його таким чином, щоб він зв'язав два погляди. Зітхнути.
— Скотт Біггс

6

Додайте просте додавання плаваючої кнопки дій за допомогою TextView, надаючи закруглений xml фон. - Додати компіляцію com.android.support:design:23.1.1у файл gradle

  • Використовуйте CoordinatorLayout як перегляд кореня.
  • Перед тим, як закінчити макет координатора, введіть textView.
  • Всередині малювання намалюйте коло.

Коло Xml є

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <solid
        android:color="@color/colorPrimary"/>
    <size
        android:width="30dp"
        android:height="30dp"/>
</shape>

Макет xml є

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="5"
    >

    <RelativeLayout
        android:id="@+id/viewA"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="1.6"
        android:background="@drawable/contact_bg"
        android:gravity="center_horizontal|center_vertical"
        >
        </RelativeLayout>

    <LinearLayout
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="3.4"
        android:orientation="vertical"
        android:padding="16dp"
        android:weightSum="10"
        >

        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            >
            </LinearLayout>

        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="Name"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:id="@+id/name"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="Ritesh Kumar Singh"
                android:singleLine="true"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            </LinearLayout>



        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="Phone"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:id="@+id/number"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="8283001122"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:singleLine="true"
                android:padding="3dp"
                />

        </LinearLayout>



        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="Email"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="ritesh.singh@betasoftsystems.com"
                android:textSize="22dp"
                android:singleLine="true"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

        </LinearLayout>


        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="City"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="Panchkula"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:singleLine="true"
                android:padding="3dp"
                />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>


    <TextView
        android:id="@+id/floating"
        android:transitionName="@string/transition_name_circle"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="16dp"
        android:clickable="false"
        android:background="@drawable/circle"
        android:elevation="10dp"
        android:text="R"
        android:textSize="40dp"
        android:gravity="center"
        android:textColor="@android:color/black"
        app:layout_anchor="@id/viewA"
        app:layout_anchorGravity="bottom"/>

        </android.support.design.widget.CoordinatorLayout>

Клацніть тут, щоб побачити, як це буде виглядати


5

Додайте це до файлу gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile 'com.android.support:design:23.0.1'
}

Це до вашої activity_main.xml

<android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:id="@+id/viewOne"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="0.6"
                android:background="@android:color/holo_blue_light"
                android:orientation="horizontal"/>

            <LinearLayout
                android:id="@+id/viewTwo"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="0.4"
                android:background="@android:color/holo_orange_light"
                android:orientation="horizontal"/>

        </LinearLayout>

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/floatingButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:clickable="true"
            android:src="@drawable/ic_done"
            app:layout_anchor="@id/viewOne"
            app:layout_anchorGravity="bottom|right|end"
            app:backgroundTint="#FF0000"
            app:rippleColor="#FFF" />

    </android.support.design.widget.CoordinatorLayout>

Ви можете знайти повний приклад з проектом студії Android для завантаження на веб- сайті http://www.ahotbrew.com/android-floating-action-button/


1

ось робочий код.

Я використовую appBarLayout для прив’язки моєї плаваючої кнопки Дія. сподіваюся, що це може бути корисним.

XML КОД.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_height="192dp"
        android:layout_width="match_parent">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:toolbarId="@+id/toolbar"
            app:titleEnabled="true"
            app:layout_scrollFlags="scroll|enterAlways|exitUntilCollapsed"
            android:id="@+id/collapsingbar"
            app:contentScrim="?attr/colorPrimary">

            <android.support.v7.widget.Toolbar
                app:layout_collapseMode="pin"
                android:id="@+id/toolbarItemDetailsView"
                android:layout_height="?attr/actionBarSize"
                android:layout_width="match_parent"></android.support.v7.widget.Toolbar>
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context="com.example.rktech.myshoplist.Item_details_views">
            <RelativeLayout
                android:orientation="vertical"
                android:focusableInTouchMode="true"
                android:layout_width="match_parent"
                android:layout_height="match_parent">


                <!--Put Image here -->
                <ImageView
                    android:visibility="gone"
                    android:layout_marginTop="56dp"
                    android:layout_width="match_parent"
                    android:layout_height="230dp"
                    android:scaleType="centerCrop"
                    android:src="@drawable/third" />


                <ScrollView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_gravity="center"
                        android:orientation="vertical">

                        <android.support.v7.widget.CardView
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            app:cardCornerRadius="4dp"
                            app:cardElevation="4dp"
                            app:cardMaxElevation="6dp"
                            app:cardUseCompatPadding="true">

                            <RelativeLayout
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_margin="8dp"
                                android:padding="3dp">


                                <LinearLayout
                                    android:layout_width="match_parent"
                                    android:layout_height="match_parent"
                                    android:orientation="vertical">


                                    <TextView
                                        android:id="@+id/txtDetailItemTitle"
                                        style="@style/TextAppearance.AppCompat.Title"
                                        android:layout_width="match_parent"
                                        android:layout_height="wrap_content"
                                        android:layout_marginLeft="4dp"
                                        android:text="Title" />

                                    <LinearLayout
                                        android:layout_width="match_parent"
                                        android:layout_height="match_parent"
                                        android:layout_marginTop="8dp"
                                        android:orientation="horizontal">

                                        <TextView
                                            android:id="@+id/txtDetailItemSeller"
                                            style="@style/TextAppearance.AppCompat.Subhead"
                                            android:layout_width="wrap_content"
                                            android:layout_height="wrap_content"
                                            android:layout_marginLeft="4dp"
                                            android:layout_weight="1"
                                            android:text="Shope Name" />

                                        <TextView
                                            android:id="@+id/txtDetailItemDate"
                                            style="@style/TextAppearance.AppCompat.Subhead"
                                            android:layout_width="wrap_content"
                                            android:layout_height="wrap_content"
                                            android:layout_marginRight="4dp"
                                            android:gravity="right"
                                            android:text="Date" />


                                    </LinearLayout>

                                    <TextView
                                        android:id="@+id/txtDetailItemDescription"
                                        style="@style/TextAppearance.AppCompat.Medium"
                                        android:layout_width="match_parent"
                                        android:minLines="5"
                                        android:layout_height="wrap_content"
                                        android:layout_marginLeft="4dp"
                                        android:layout_marginTop="16dp"
                                        android:text="description" />

                                    <LinearLayout
                                        android:layout_width="match_parent"
                                        android:layout_height="wrap_content"
                                        android:layout_marginBottom="8dp"
                                        android:orientation="horizontal">

                                        <TextView
                                            android:id="@+id/txtDetailItemQty"
                                            style="@style/TextAppearance.AppCompat.Medium"
                                            android:layout_width="wrap_content"
                                            android:layout_height="wrap_content"
                                            android:layout_marginLeft="4dp"
                                            android:layout_weight="1"
                                            android:text="Qunatity" />

                                        <TextView
                                            android:id="@+id/txtDetailItemMessure"
                                            style="@style/TextAppearance.AppCompat.Medium"
                                            android:layout_width="wrap_content"
                                            android:layout_height="wrap_content"
                                            android:layout_marginRight="4dp"
                                            android:layout_weight="1"
                                            android:gravity="right"
                                            android:text="Messure in Gram" />
                                    </LinearLayout>


                                    <TextView
                                        android:id="@+id/txtDetailItemPrice"
                                        style="@style/TextAppearance.AppCompat.Headline"
                                        android:layout_width="match_parent"
                                        android:layout_height="wrap_content"
                                        android:layout_marginRight="4dp"
                                        android:layout_weight="1"
                                        android:gravity="right"
                                        android:text="Price" />
                                </LinearLayout>

                            </RelativeLayout>
                        </android.support.v7.widget.CardView>
                    </RelativeLayout>
                </ScrollView>
            </RelativeLayout>

        </android.support.constraint.ConstraintLayout>

    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        app:layout_anchor="@id/appbar"
        app:fabSize="normal"
        app:layout_anchorGravity="bottom|right|end"
        android:layout_marginEnd="@dimen/_6sdp"
        android:src="@drawable/ic_done_black_24dp"
        android:layout_height="wrap_content" />

</android.support.design.widget.CoordinatorLayout>

Тепер, якщо ви вставите вище коду. ви побачите наступний результат на своєму пристрої. Зображення результату

Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.