• Stars
    star
    18,141
  • Rank 1,371 (Top 0.03 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created almost 8 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Flexbox for Android

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:

  • 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

      Flex Direction explanation

  • 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)

      Flex Wrap explanation

  • 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

      Justify Content explanation

  • 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)

      Align Items explanation

  • 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

      Align Content explanation

  • 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 or column_rebase).
  • 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 or column_rebase).
  • 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" or alignContent="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" />

    Dividers beginning and middle

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.

      Order explanation

  • 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 positive layout_flexGrow values, the remaining free space is distributed depending on the proportion of their declared layout_flexGrow value. (Similar to the layout_weight attribute in the LinearLayout) If not specified, 0 is set as a default value.

      Flex Grow explanation

  • 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.

      Flex Shrink explanation

  • 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 than auto, the cross axis alignment is overridden for this child. Possible values are:

      • auto (default)
      • flex_start
      • flex_end
      • center
      • baseline
      • stretch

      Align Self explanation

  • 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 (or layout_height) is overridden by the calculated value from this attribute. This attribute is only effective when the parent's length is definite (MeasureSpec mode is MeasureSpec.EXACTLY). The default value is -1, which means not set.

      Flex basis percent explanation

  • 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 the layout_flexShrink attribute.

      Min width explanation

  • 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 the layout_flexGrow attribute.

      Max width explanation

  • layout_wrapBefore (boolean)

    • This attribute forces a flex line wrapping, the default value is false. i.e. if this is set to true 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 the flex_wrap attribute is set to nowrap. 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.

      Wrap before explanation

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 the flex-direction and flex-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 the flex-grow, flex-shrink and flex-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 and flex-basis property in the CSS are used to determine the initial length of an individual flex item. The flex-basis property accepts width values such as 1em, 10px, and content as strings as well as percentage values such as 10% and 30%. 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 the flexDirection). 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 the alignItems is expensive because the children of FlexboxLayout 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

More Repositories

1

material-design-icons

Material Design icons by Google
49,605
star
2

guava

Google core libraries for Java
Java
48,313
star
3

zx

A tool for writing better scripts
JavaScript
37,928
star
4

styleguide

Style guides for Google-originated open-source projects
HTML
36,487
star
5

leveldb

LevelDB is a fast key-value storage library written at Google that provides an ordered mapping from string keys to string values.
C++
33,564
star
6

material-design-lite

Material Design Components in HTML/CSS/JS
HTML
32,280
star
7

googletest

GoogleTest - Google Testing and Mocking Framework
C++
32,215
star
8

jax

Composable transformations of Python+NumPy programs: differentiate, vectorize, JIT to GPU/TPU, and more
Python
27,869
star
9

python-fire

Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object.
Python
26,112
star
10

comprehensive-rust

This is the Rust course used by the Android team at Google. It provides you the material to quickly teach Rust.
Rust
25,907
star
11

mediapipe

Cross-platform, customizable ML solutions for live and streaming media.
C++
25,320
star
12

gson

A Java serialization/deserialization library to convert Java Objects into JSON and back
Java
22,856
star
13

flatbuffers

FlatBuffers: Memory Efficient Serialization Library
C++
21,883
star
14

iosched

The Google I/O Android App
Kotlin
21,792
star
15

ExoPlayer

An extensible media player for Android
Java
21,465
star
16

eng-practices

Google's Engineering Practices documentation
19,741
star
17

web-starter-kit

Web Starter Kit - a workflow for multi-device websites
HTML
18,434
star
18

fonts

Font files available from Google Fonts, and a public issue tracker for all things Google Fonts
HTML
17,563
star
19

filament

Filament is a real-time physically based rendering engine for Android, iOS, Windows, Linux, macOS, and WebGL2
C++
16,946
star
20

cadvisor

Analyzes resource usage and performance characteristics of running containers.
Go
16,273
star
21

libphonenumber

Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers.
C++
15,728
star
22

gvisor

Application Kernel for Containers
Go
15,047
star
23

WebFundamentals

Former git repo for WebFundamentals on developers.google.com
JavaScript
13,842
star
24

yapf

A formatter for Python files
Python
13,560
star
25

tink

Tink is a multi-language, cross-platform, open source library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse.
Java
13,318
star
26

deepdream

13,212
star
27

brotli

Brotli compression format
TypeScript
12,921
star
28

guetzli

Perceptual JPEG encoder
C++
12,863
star
29

guice

Guice (pronounced 'juice') is a lightweight dependency injection framework for Java 11 and above, brought to you by Google.
Java
12,342
star
30

wire

Compile-time Dependency Injection for Go
Go
12,222
star
31

blockly

The web-based visual programming editor.
TypeScript
12,067
star
32

sanitizers

AddressSanitizer, ThreadSanitizer, MemorySanitizer
C
10,754
star
33

grumpy

Grumpy is a Python to Go source code transcompiler and runtime.
Go
10,464
star
34

or-tools

Google's Operations Research tools:
C++
10,405
star
35

dopamine

Dopamine is a research framework for fast prototyping of reinforcement learning algorithms.
Jupyter Notebook
10,367
star
36

auto

A collection of source code generators for Java.
Java
10,234
star
37

go-github

Go library for accessing the GitHub v3 API
Go
9,941
star
38

oss-fuzz

OSS-Fuzz - continuous fuzzing for open source software.
Shell
9,859
star
39

go-cloud

The Go Cloud Development Kit (Go CDK): A library and tools for open cloud development in Go.
Go
9,314
star
40

sentencepiece

Unsupervised text tokenizer for Neural Network-based text generation.
C++
8,657
star
41

re2

RE2 is a fast, safe, thread-friendly alternative to backtracking regular expression engines like those used in PCRE, Perl, and Python. It is a C++ library.
C++
8,190
star
42

traceur-compiler

Traceur is a JavaScript.next-to-JavaScript-of-today compiler
JavaScript
8,182
star
43

tsunami-security-scanner

Tsunami is a general purpose network security scanner with an extensible plugin system for detecting high severity vulnerabilities with high confidence.
Java
8,086
star
44

trax

Trax — Deep Learning with Clear Code and Speed
Python
7,943
star
45

skia

Skia is a complete 2D graphic library for drawing Text, Geometries, and Images.
C++
7,874
star
46

benchmark

A microbenchmark support library
C++
7,812
star
47

android-classyshark

Android and Java bytecode viewer
Java
7,468
star
48

pprof

pprof is a tool for visualization and analysis of profiling data
Go
7,408
star
49

closure-compiler

A JavaScript checker and optimizer.
Java
7,245
star
50

agera

Reactive Programming for Android
Java
7,227
star
51

accompanist

A collection of extension libraries for Jetpack Compose
Kotlin
7,190
star
52

magika

Detect file content types with deep learning
Python
7,171
star
53

flutter-desktop-embedding

Experimental plugins for Flutter for Desktop
C++
7,109
star
54

latexify_py

A library to generate LaTeX expression from Python code.
Python
6,953
star
55

diff-match-patch

Diff Match Patch is a high-performance library in multiple languages that manipulates plain text.
Python
6,918
star
56

lovefield

Lovefield is a relational database for web apps. Written in JavaScript, works cross-browser. Provides SQL-like APIs that are fast, safe, and easy to use.
JavaScript
6,847
star
57

glog

C++ implementation of the Google logging module
C++
6,797
star
58

jsonnet

Jsonnet - The data templating language
Jsonnet
6,742
star
59

error-prone

Catch common Java mistakes as compile-time errors
Java
6,690
star
60

model-viewer

Easily display interactive 3D models on the web and in AR!
TypeScript
6,473
star
61

gops

A tool to list and diagnose Go processes currently running on your system
Go
6,375
star
62

draco

Draco is a library for compressing and decompressing 3D geometric meshes and point clouds. It is intended to improve the storage and transmission of 3D graphics.
C++
6,188
star
63

automl

Google Brain AutoML
Jupyter Notebook
6,150
star
64

gopacket

Provides packet processing capabilities for Go
Go
6,082
star
65

physical-web

The Physical Web: walk up and use anything
Java
6,017
star
66

j2objc

A Java to iOS Objective-C translation tool and runtime.
Java
5,976
star
67

grafika

Grafika test app
Java
5,964
star
68

snappy

A fast compressor/decompressor
C++
5,940
star
69

ios-webkit-debug-proxy

A DevTools proxy (Chrome Remote Debugging Protocol) for iOS devices (Safari Remote Web Inspector).
C
5,848
star
70

osv-scanner

Vulnerability scanner written in Go which uses the data provided by https://osv.dev
Go
5,821
star
71

seesaw

Seesaw v2 is a Linux Virtual Server (LVS) based load balancing platform.
Go
5,599
star
72

seq2seq

A general-purpose encoder-decoder framework for Tensorflow
Python
5,577
star
73

EarlGrey

🍵 iOS UI Automation Test Framework
Objective-C
5,570
star
74

flax

Flax is a neural network library for JAX that is designed for flexibility.
Python
5,493
star
75

google-java-format

Reformats Java source code to comply with Google Java Style.
Java
5,366
star
76

wireit

Wireit upgrades your npm/pnpm/yarn scripts to make them smarter and more efficient.
TypeScript
5,280
star
77

battery-historian

Battery Historian is a tool to analyze battery consumers using Android "bugreport" files.
Go
5,249
star
78

clusterfuzz

Scalable fuzzing infrastructure.
Python
5,201
star
79

bbr

5,156
star
80

gumbo-parser

An HTML5 parsing library in pure C99
HTML
5,141
star
81

syzkaller

syzkaller is an unsupervised coverage-guided kernel fuzzer
Go
5,111
star
82

git-appraise

Distributed code review system for Git repos
Go
5,090
star
83

google-authenticator

Open source version of Google Authenticator (except the Android app)
Java
5,077
star
84

gemma.cpp

lightweight, standalone C++ inference engine for Google's Gemma models.
C++
5,076
star
85

uuid

Go package for UUIDs based on RFC 4122 and DCE 1.1: Authentication and Security Services.
Go
4,994
star
86

gemma_pytorch

The official PyTorch implementation of Google's Gemma models
Python
4,920
star
87

gts

☂️ TypeScript style guide, formatter, and linter.
TypeScript
4,890
star
88

closure-library

Google's common JavaScript library
JavaScript
4,837
star
89

cameraview

[DEPRECATED] Easily integrate Camera features into your Android app
Java
4,734
star
90

grr

GRR Rapid Response: remote live forensics for incident response
Python
4,641
star
91

liquidfun

2D physics engine for games
C++
4,559
star
92

pytype

A static type analyzer for Python code
Python
4,528
star
93

gxui

An experimental Go cross platform UI library.
Go
4,450
star
94

bloaty

Bloaty: a size profiler for binaries
C++
4,386
star
95

clasp

🔗 Command Line Apps Script Projects
TypeScript
4,336
star
96

ko

Build and deploy Go applications on Kubernetes
Go
4,329
star
97

santa

A binary authorization and monitoring system for macOS
Objective-C
4,288
star
98

google-ctf

Google CTF
Go
4,246
star
99

tamperchrome

Tamper Dev is an extension that allows you to intercept and edit HTTP/HTTPS requests and responses as they happen without the need of a proxy. Works across all operating systems (including Chrome OS).
TypeScript
4,148
star
100

end-to-end

End-To-End is a crypto library to encrypt, decrypt, digital sign, and verify signed messages (implementing OpenPGP)
JavaScript
4,126
star