flexbox-layout README

The project's README from github.com/google/flexbox-layout. As one markdown file: README.md.

FlexboxLayout

Circle CI

FlexboxLayout is a library project which brings the similar capabilities of CSS Flexible Box Layout Module to Android.

Installation

Add the following dependency to your build.gradle file:

dependencies {
    implementation 'com.google.android.flexbox:flexbox:3.0.0'
}

Starting from 3.0.0, the groupId is changed to com.google.android.flexbox in preparation to uploading the artifacts to google maven. You can still download the artifacts from jcenter for the past versions with the prior groupId (com.google.android), but migrating the library 3.0.0 is recommended.

Note that the default values for alignItems and alignContent for FlexboxLayout have been changed from stretch to flex_start starting from 2.0.0, it may break the existing apps. Please make sure to set stretch explicitly if you want to apply the behavior of stretch.

Note that starting from 1.1.0, the library is expeced to use with AndroidX. Please migrate to AndroidX if you use 1.1.0 or above.

Please use 1.0.0 if you haven't migrated to AndroidX.

Usage

There are two ways of using Flexbox in your layout.

FlexboxLayout

The first one is FlexboxLayout that extends the ViewGroup like LinearLayout and RelativeLayout. You can specify the attributes from a layout XML like:

<com.google.android.flexbox.FlexboxLayout
    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"
    app:flexWrap="wrap"
    app:alignItems="stretch"
    app:alignContent="stretch" >

    <TextView
        android:id="@+id/textview1"
        android:layout_width="120dp"
        android:layout_height="80dp"
        app:layout_flexBasisPercent="50%"
        />

    <TextView
        android:id="@+id/textview2"
        android:layout_width="80dp"
        android:layout_height="80dp"
        app:layout_alignSelf="center"
        />

    <TextView
        android:id="@+id/textview3"
        android:layout_width="160dp"
        android:layout_height="80dp"
        app:layout_alignSelf="flex_end"
        />
</com.google.android.flexbox.FlexboxLayout>

Or from code like:

FlexboxLayout flexboxLayout = (FlexboxLayout) findViewById(R.id.flexbox_layout);
flexboxLayout.setFlexDirection(FlexDirection.ROW);

View view = flexboxLayout.getChildAt(0);
FlexboxLayout.LayoutParams lp = (FlexboxLayout.LayoutParams) view.getLayoutParams();
lp.setOrder(-1);
lp.setFlexGrow(2);
view.setLayoutParams(lp);

FlexboxLayoutManager (within RecyclerView)

The second one is FlexboxLayoutManager that can be used within RecyclerView.

RecyclerView recyclerView = (RecyclerView) context.findViewById(R.id.recyclerview);
FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(context);
layoutManager.setFlexDirection(FlexDirection.COLUMN);
layoutManager.setJustifyContent(JustifyContent.FLEX_END);
recyclerView.setLayoutManager(layoutManager);

or for the attributes for the children of the FlexboxLayoutManager you can do like:

mImageView.setImageDrawable(drawable);
ViewGroup.LayoutParams lp = mImageView.getLayoutParams();
if (lp instanceof FlexboxLayoutManager.LayoutParams) {
    FlexboxLayoutManager.LayoutParams flexboxLp = (FlexboxLayoutManager.LayoutParams) lp;
    flexboxLp.setFlexGrow(1.0f);
    flexboxLp.setAlignSelf(AlignSelf.FLEX_END);
}

The advantage of using FlexboxLayoutManager is that it recycles the views that go off the screen for reuse for the views that are appearing as the user scrolls instead of inflating every individual view, which consumes much less memory especially when the number of items contained in the Flexbox container is large.

FlexboxLayoutManager in action

Supported attributes/features comparison

Due to some characteristics of RecyclerView, some Flexbox attributes are not available/not implemented to the FlexboxLayoutManager. Here is a quick overview of the attributes/features comparison between the two implementations.

Attribute / Feature FlexboxLayout FlexboxLayoutManager (RecyclerView)
flexDirection Check Check
flexWrap Check Check (except wrap_reverse)
justifyContent Check Check
alignItems Check Check
alignContent Check -
layout_order Check -
layout_flexGrow Check Check
layout_flexShrink Check Check
layout_alignSelf Check Check
layout_flexBasisPercent Check Check
layout_(min/max)Width Check Check
layout_(min/max)Height Check Check
layout_wrapBefore Check Check
Divider Check Check
View recycling - Check
Scrolling *1 Check

*1 Partially possible by wrapping it with ScrollView. But it isn't likely to work with a large set of views inside the layout. Because it doesn't consider view recycling.

Supported attributes

Attributes for the FlexboxLayout:

Attributes for the children of a FlexboxLayout

Others

Known differences from the original CSS specification

This library tries to achieve the same capabilities of the original Flexible Box specification as much as possible, but due to some reasons such as the way specifying attributes can't be the same between CSS and Android XML, there are some known differences from the original specification.

(1) There is no flex-flow equivalent attribute

(2) There is no flex equivalent attribute

(3) layout_flexBasisPercent is introduced instead of flexBasis

(4) layout_wrapBefore is introduced.

(5) Default values for alignItems and alignContent are set to flex_start instead of stretch.

Xamarin Binding

Xamarin binding is now available on NuGet thanks to @btripp

Demo apps

Flexbox Playground demo app

The demo-playground module works as a playground demo app for trying various values for the supported attributes. You can install it by

./gradlew demo-playground:installDebug

The demo-cat-gallery module showcases the usage of the FlexboxLayoutManager inside the RecyclerView that handles various sizes of views aligned nicely regardless of the device width like the Google Photo app without loading all the images on the memory. Thus compared to using the {@link FlexboxLayout}, it's much less likely to abuse the memory, which sometimes leads to the OutOfMemoryError.

./gradlew demo-cat-gallery:installDebug

How to make contributions

Please read and follow the steps in CONTRIBUTING.md

License

Please see LICENSE

flexbox-layout (google/flexbox-layout)

Searching Database…

18.3K ·GitHub
archived
Что это такое?FlexboxLayout — это open-source библиотека для Android, которая переносит возможности модуля CSS Flexible Box Layout (flexbox) в разметку Android-приложений.
Это библиотека, которую я подключаю к проекту, или отдельное приложение?Это библиотека, которую вы подключаете как Gradle-зависимость. В её основе лежит FlexboxLayout — ViewGroup, как LinearLayout или RelativeLayout, а также FlexboxLayoutManager для использования внутри RecyclerView.
Как добавить её в Android-проект?Добавьте зависимость flexbox в ваш build.gradle. Начиная с версии 3.0.0 groupId — это com.google.android.flexbox, а артефакты публикуются в Google Maven; старые версии по-прежнему можно скачать с jcenter под прежним groupId.
Нужно ли сначала перевести мой проект на AndroidX?Для свежих версий — да: начиная с 1.1.0 библиотека требует AndroidX. Если ваш проект ещё не переведён, зафиксируйте версию 1.0.0.
Есть ли подводные камни при обновлении, о которых стоит знать?В версии 2.0.0 значения по умолчанию для alignItems и alignContent изменились со stretch на flexstart, что может незаметно сломать существующие разметки — задавайте stretch явно, если вы рассчитываете на прежнее поведение.
Это строго для нативного Android или работает где-то ещё?Она создана для нативных Android-приложений. Также на NuGet доступен биндинг для Xamarin — для мобильных проектов на Xamarin.
Какие есть два способа использовать flexbox в разметке?Как FlexboxLayout — обычную ViewGroup, которую настраивают через layout XML или код, — либо как FlexboxLayoutManager, который передаётся в RecyclerView, когда нужен прокручиваемый список flex-элементов.
Почему стоит выбрать FlexboxLayoutManager вместо обычного FlexboxLayout?Он переиспользует (рециклирует) view, ушедшие за экран, вместо того чтобы создавать каждый дочерний элемент заново, поэтому память экономится, когда в контейнере много элементов. Обратная сторона: такие атрибуты, как wrapreverse, alignContent и разделители, там не поддерживаются, а прокручивать большую разметку без рециклинга непрактично.
Насколько точно соблюдается спецификация CSS flexbox?Довольно точно, но есть задокументированные отличия: нет атрибутов flex-flow и flex-shorthand, layoutflexBasisPercent принимает только проценты вместо значений flex-basis, зато есть дополнительный атрибут layoutwrapBefore, который принудительно переносит строки. Значения по умолчанию тоже отличаются — flexstart вместо stretch.
Репозиторий до сих пор активно поддерживается?Нет — на GitHub google/flexbox-layout помечен как архивный, код доступен только для чтения и больше не развивается. Уже опубликованные артефакты по-прежнему доступны в Google Maven.
Creator
google
Size
48.2 MB
Stars
18.3K
Age
10y
Commits · 90 Days