Top Related Projects
Yoga is an embeddable layout engine targeting web standards.
Epoxy is an Android library for building complex screens in a RecyclerView
A powerful image downloading and caching library for Android
An image loading and caching library for Android focused on smooth scrolling
RxJava – Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.
A type-safe HTTP client for Android and the JVM
Quick Overview
Flexbox-layout is an Android library that brings the power of CSS Flexbox to Android, allowing developers to create flexible and responsive layouts with ease. It provides a set of custom views that implement the Flexbox specification, making it simpler to design complex user interfaces for Android applications.
Pros
- Simplifies the creation of complex, responsive layouts in Android
- Provides a familiar layout system for web developers transitioning to Android
- Offers better performance compared to nested LinearLayouts
- Supports most features of the CSS Flexbox specification
Cons
- Requires learning a new layout system for developers unfamiliar with Flexbox
- May have a slight learning curve for those used to traditional Android layouts
- Not part of the Android SDK, requiring an additional dependency
- Some advanced Flexbox features might not be fully supported
Code Examples
- Creating a simple Flexbox layout:
<com.google.android.flexbox.FlexboxLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:flexDirection="row"
app:justifyContent="space_between">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 3" />
</com.google.android.flexbox.FlexboxLayout>
- Using Flexbox properties programmatically:
val flexboxLayout = FlexboxLayout(context)
flexboxLayout.flexDirection = FlexDirection.ROW
flexboxLayout.justifyContent = JustifyContent.SPACE_BETWEEN
val layoutParams = FlexboxLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
layoutParams.order = -1 // Change the order of the view
layoutParams.flexGrow = 2f // Allow the view to grow
val childView = TextView(context)
childView.layoutParams = layoutParams
flexboxLayout.addView(childView)
- Creating a wrapping grid layout:
<com.google.android.flexbox.FlexboxLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:flexWrap="wrap"
app:alignItems="center"
app:alignContent="space_around">
<!-- Add multiple child views here -->
</com.google.android.flexbox.FlexboxLayout>
Getting Started
To use flexbox-layout in your Android project:
- Add the dependency to your app's
build.gradle
file:
dependencies {
implementation 'com.google.android.flexbox:flexbox:3.0.0'
}
-
Use
FlexboxLayout
in your XML layouts or create it programmatically in your Kotlin/Java code. -
Set Flexbox properties using XML attributes or programmatically to achieve the desired layout behavior.
Competitor Comparisons
Yoga is an embeddable layout engine targeting web standards.
Pros of Yoga
- Cross-platform support (Android, iOS, Web)
- More flexible layout system with additional properties
- Better performance due to C++ core implementation
Cons of Yoga
- Steeper learning curve due to more complex API
- Less native integration with Android views
- Requires additional setup and configuration
Code Comparison
Flexbox-layout:
FlexboxLayout flexboxLayout = new FlexboxLayout(context);
flexboxLayout.setFlexDirection(FlexDirection.ROW);
flexboxLayout.setJustifyContent(JustifyContent.FLEX_START);
Yoga:
YogaNode root = new YogaNode();
root.setFlexDirection(YogaFlexDirection.ROW);
root.setJustifyContent(YogaJustify.FLEX_START);
Summary
Flexbox-layout is a simpler, Android-specific layout library that integrates well with existing Android views. Yoga offers cross-platform support and more advanced layout capabilities but requires additional setup and has a steeper learning curve. Both libraries provide similar basic flexbox functionality, but Yoga's C++ core implementation may offer better performance for complex layouts.
Epoxy is an Android library for building complex screens in a RecyclerView
Pros of Epoxy
- More comprehensive UI building solution, offering advanced features like view holders, data binding, and carousel layouts
- Better suited for complex, dynamic UI scenarios with heterogeneous view types
- Provides built-in support for RecyclerView and efficient list management
Cons of Epoxy
- Steeper learning curve due to its more complex architecture and concepts
- May be overkill for simpler layouts or projects that don't require advanced UI features
- Requires more setup and boilerplate code compared to Flexbox Layout
Code Comparison
Flexbox Layout:
<com.google.android.flexbox.FlexboxLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:flexWrap="wrap"
app:alignItems="center">
<!-- Child views -->
</com.google.android.flexbox.FlexboxLayout>
Epoxy:
class MyEpoxyController : EpoxyController() {
override fun buildModels() {
header {
id("header")
title("My Header")
}
// Add more models
}
}
Summary
Flexbox Layout focuses on flexible layouts using CSS Flexbox principles, while Epoxy provides a more comprehensive solution for building complex, dynamic UIs. Flexbox Layout is simpler to use for basic layouts, whereas Epoxy offers advanced features for managing complex view hierarchies and data binding. Choose based on your project's complexity and requirements.
A powerful image downloading and caching library for Android
Pros of Picasso
- Focuses on image loading and caching, providing a powerful solution for handling images in Android apps
- Offers automatic memory and disk caching, reducing the burden on developers
- Supports image transformations and placeholders out of the box
Cons of Picasso
- Limited to image handling, unlike Flexbox-layout which is a general-purpose layout system
- May require additional libraries for complex UI layouts
- Less flexibility in creating responsive designs compared to Flexbox-layout
Code Comparison
Picasso (image loading):
Picasso.get()
.load("https://example.com/image.jpg")
.into(imageView);
Flexbox-layout (layout creation):
<com.google.android.flexbox.FlexboxLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- Child views -->
</com.google.android.flexbox.FlexboxLayout>
Summary
Picasso excels in image handling and caching for Android apps, while Flexbox-layout provides a flexible layout system. Picasso simplifies image loading tasks but is limited to that specific functionality. Flexbox-layout offers more versatility in creating responsive layouts but requires more manual setup for image handling. The choice between the two depends on the specific needs of your project, with Picasso being ideal for image-heavy apps and Flexbox-layout for complex, responsive UI designs.
An image loading and caching library for Android focused on smooth scrolling
Pros of Glide
- Specialized for image loading and caching in Android apps
- Extensive features for image manipulation and display
- Large community and ecosystem with many extensions
Cons of Glide
- Limited to image handling, not a general-purpose layout solution
- May introduce additional overhead for simple image loading tasks
- Steeper learning curve for advanced features
Code Comparison
Flexbox-layout (XML layout):
<com.google.android.flexbox.FlexboxLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:flexWrap="wrap"
app:alignItems="stretch"
app:alignContent="stretch" >
<!-- Child views -->
</com.google.android.flexbox.FlexboxLayout>
Glide (Java):
Glide.with(context)
.load(imageUrl)
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(imageView);
Summary
Flexbox-layout and Glide serve different purposes in Android development. Flexbox-layout is a layout manager that brings flexible box capabilities to Android, allowing for complex and responsive layouts. Glide, on the other hand, is an image loading and caching library that simplifies the process of displaying images in Android applications. While Flexbox-layout focuses on arranging views, Glide specializes in efficient image handling, offering features like caching, resizing, and transformations.
RxJava – Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.
Pros of RxJava
- Powerful reactive programming library for handling asynchronous data streams
- Extensive set of operators for composing and transforming observables
- Supports multi-threading and concurrency out of the box
Cons of RxJava
- Steeper learning curve compared to flexbox-layout
- Can lead to complex code if not used carefully
- Potential for memory leaks if not properly managed
Code Comparison
RxJava:
Observable.just(1, 2, 3, 4, 5)
.map(n -> n * 2)
.filter(n -> n > 5)
.subscribe(System.out::println);
flexbox-layout:
<com.google.android.flexbox.FlexboxLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:flexWrap="wrap"
app:alignItems="flex_start"
app:alignContent="flex_start">
<!-- Child views -->
</com.google.android.flexbox.FlexboxLayout>
Summary
RxJava is a reactive programming library for handling asynchronous data streams, while flexbox-layout is a layout manager for Android that implements CSS Flexible Box Layout. RxJava offers powerful tools for managing complex asynchronous operations but has a steeper learning curve. flexbox-layout provides a flexible way to arrange UI elements in Android apps, with a simpler API focused on layout management.
A type-safe HTTP client for Android and the JVM
Pros of Retrofit
- Simplifies HTTP API interactions in Android and Java applications
- Supports various data formats (JSON, XML, etc.) and authentication mechanisms
- Extensive documentation and community support
Cons of Retrofit
- Limited to HTTP-based APIs, unlike Flexbox-layout's UI focus
- Requires more setup and configuration compared to Flexbox-layout's simplicity
- May introduce additional dependencies for certain features
Code Comparison
Retrofit example:
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
Flexbox-layout example:
<com.google.android.flexbox.FlexboxLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:flexWrap="wrap"
app:alignItems="stretch"
app:alignContent="stretch" >
<!-- Child views here -->
</com.google.android.flexbox.FlexboxLayout>
While both libraries serve different purposes, Retrofit excels in API communication, whereas Flexbox-layout focuses on flexible UI layouts. Retrofit offers powerful networking capabilities but requires more setup, while Flexbox-layout provides an easier way to create responsive layouts with minimal configuration.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
FlexboxLayout
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.
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 | ||
flexWrap | (except wrap_reverse ) | |
justifyContent | ||
alignItems | ||
alignContent | - | |
layout_order | - | |
layout_flexGrow | ||
layout_flexShrink | ||
layout_alignSelf | ||
layout_flexBasisPercent | ||
layout_(min/max)Width | ||
layout_(min/max)Height | ||
layout_wrapBefore | ||
Divider | ||
View recycling | - | |
Scrolling | *1 |
*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:
-
flexDirection
-
This attribute determines the direction of the main axis (and the cross axis, perpendicular to the main axis). The direction children items are placed inside the Flexbox layout. Possible values are:
- row (default)
- row_reverse
- column
- column_reverse
-
-
flexWrap
-
This attribute controls whether the flex container is single-line or multi-line, and the direction of the cross axis. Possible values are:
- nowrap (default for FlexboxLayout)
- wrap (default for FlexboxLayoutManager)
- wrap_reverse (not supported by FlexboxLayoutManager)
-
-
justifyContent
-
This attribute controls the alignment along the main axis. Possible values are:
- flex_start (default)
- flex_end
- center
- space_between
- space_around
- space_evenly
-
-
alignItems
-
This attribute controls the alignment along the cross axis. Possible values are:
- flex_start (default for FlexboxLayout)
- flex_end
- center
- baseline
- stretch (default for FlexboxLayoutManager)
-
-
alignContent
-
This attribute controls the alignment of the flex lines in the flex container. Possible values are:
- flex_start (default)
- flex_end
- center
- space_between
- space_around
- stretch
-
-
showDividerHorizontal (one or more of
none | beginning | middle | end
) -
dividerDrawableHorizontal (reference to a drawable)
- Puts horizontal dividers between flex lines (or flex items when flexDirection
is set to
column
orcolumn_rebase
).
- Puts horizontal dividers between flex lines (or flex items when flexDirection
is set to
-
showDividerVertical (one or more of
none | beginning | middle | end
) -
dividerDrawableVertical (reference to a drawable)
- Puts vertical dividers between flex items (or flex lines when flexDirection
is set to
column
orcolumn_rebase
).
- Puts vertical dividers between flex items (or flex lines when flexDirection
is set to
-
showDivider (one or more of
none | beginning | middle | end
) -
dividerDrawable (reference to a drawable)
- Shorthand for setting both horizontal and vertical dividers. Note that if used with other attributes
(such as
justifyContent="space_around"
oralignContent="space_between"
... etc) for putting spaces between flex lines or flex items, you may see unexpected spaces. Please avoid using these at the same time.
Example of putting both vertical and horizontal dividers.
res/drawable/divider.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"> <size android:width="8dp" android:height="12dp" /> <solid android:color="#44A444" /> </shape>
res/layout/content_main.xml
<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:alignContent="flex_start" app:alignItems="flex_start" app:flexWrap="wrap" app:showDivider="beginning|middle" app:dividerDrawable="@drawable/divider" > <TextView style="@style/FlexItem" android:layout_width="220dp" android:layout_height="80dp" android:text="1" /> <TextView style="@style/FlexItem" android:layout_width="120dp" android:layout_height="80dp" android:text="2" /> <TextView style="@style/FlexItem" android:layout_width="160dp" android:layout_height="80dp" android:text="3" /> <TextView style="@style/FlexItem" android:layout_width="80dp" android:layout_height="80dp" android:text="4" /> <TextView style="@style/FlexItem" android:layout_width="100dp" android:layout_height="80dp" android:text="5" />
- Shorthand for setting both horizontal and vertical dividers. Note that if used with other attributes
(such as
Attributes for the children of a FlexboxLayout
-
layout_order (integer)
-
This attribute can change how the ordering of the children views are laid out. By default, children are displayed and laid out in the same order as they appear in the layout XML. If not specified,
1
is set as a default value.
-
-
layout_flexGrow (float)
-
This attribute determines how much this child will grow if positive free space is distributed relative to the rest of other flex items included in the same flex line. If a flex item has a positive
layout_flexGrow
value, the item will take up the remaining space in the flex line. If multiple flex items in the same flex line have positivelayout_flexGrow
values, the remaining free space is distributed depending on the proportion of their declaredlayout_flexGrow
value. (Similar to thelayout_weight
attribute in theLinearLayout
) If not specified,0
is set as a default value.
-
-
layout_flexShrink (float)
-
This attribute determines how much this child will shrink if negative free space is distributed relative to the rest of other flex items included in the same flex line. If not specified,
1
is set as a default value.
-
-
layout_alignSelf
-
This attribute determines the alignment along the cross axis (perpendicular to the main axis). The alignment in the same direction can be determined by the
alignItems
in the parent, but if this is set to other thanauto
, the cross axis alignment is overridden for this child. Possible values are:- auto (default)
- flex_start
- flex_end
- center
- baseline
- stretch
-
-
layout_flexBasisPercent (fraction)
-
The initial flex item length in a fraction format relative to its parent. The initial main size of this child view is trying to be expanded as the specified fraction against the parent main size. If this value is set, the length specified from
layout_width
(orlayout_height
) is overridden by the calculated value from this attribute. This attribute is only effective when the parent's length is definite (MeasureSpec mode isMeasureSpec.EXACTLY
). The default value is-1
, which means not set.
-
-
layout_minWidth / layout_minHeight (dimension)
-
These attributes impose minimum size constraints for the children of FlexboxLayout. A child view won't shrink less than the value of these attributes (varies based on the
flexDirection
attribute as to which attribute imposes the size constraint along the main axis) regardless of thelayout_flexShrink
attribute.
-
-
layout_maxWidth / layout_maxHeight (dimension)
-
These attributes impose maximum size constraints for the children of FlexboxLayout. A child view won't be expanded more than the value of these attributes (varies based on the
flexDirection
attribute as to which attribute imposes the size constraint along the main axis) regardless of thelayout_flexGrow
attribute.
-
-
layout_wrapBefore (boolean)
-
This attribute forces a flex line wrapping, the default value is
false
. i.e. if this is set totrue
for a flex item, the item will become the first item of a flex line. (A wrapping happens regardless of the flex items being processed in the previous flex line) This attribute is ignored if theflex_wrap
attribute is set tonowrap
. The equivalent attribute isn't defined in the original CSS Flexible Box Module specification, but having this attribute is useful for Android developers. For example, to flatten the layouts when building a grid-like layout or for a situation where developers want to put a new flex line to make a semantic difference from the previous one, etc.
-
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
- Because
flex-flow
is a shorthand for setting theflex-direction
andflex-wrap
properties, specifying two attributes from a single attribute is not practical in Android.
(2) There is no flex equivalent attribute
- Likewise
flex
is a shorthand for setting theflex-grow
,flex-shrink
andflex-basis
, specifying those attributes from a single attribute is not practical.
(3) layout_flexBasisPercent
is introduced instead of
flexBasis
- Both
layout_flexBasisPercent
in this library andflex-basis
property in the CSS are used to determine the initial length of an individual flex item. Theflex-basis
property accepts width values such as1em
,10px
, andcontent
as strings as well as percentage values such as10%
and30%
.layout_flexBasisPercent
only accepts percentage values. However, specifying initial fixed width values can be done by specifying width (or height) values in layout_width (or layout_height, varies depending on theflexDirection
). Also, the same effect can be done by specifying "wrap_content" in layout_width (or layout_height) if developers want to achieve the same effect as 'content'. Thus,layout_flexBasisPercent
only accepts percentage values, which can't be done through layout_width (or layout_height) for simplicity.
(4) layout_wrapBefore
is introduced.
- The equivalent attribute doesn't exist in the CSS Flexible Box Module specification, but as explained above, Android developers will benefit by having this attribute for having more control over when a wrapping happens.
(5) Default values for alignItems
and alignContent
are set to flex_start
instead of stretch
.
- Setting
stretch
for thealignItems
is expensive because the children ofFlexboxLayout
are measured more than twice. The difference is more obvious when the layout hierarchy is deeply nested.
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
Cat gallery demo app
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
Top Related Projects
Yoga is an embeddable layout engine targeting web standards.
Epoxy is an Android library for building complex screens in a RecyclerView
A powerful image downloading and caching library for Android
An image loading and caching library for Android focused on smooth scrolling
RxJava – Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.
A type-safe HTTP client for Android and the JVM
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot