Android Flexbox Layout Example

FlexboxLayout is a google open source project. It’s aimed to implement CSS3 Flexbox style sheet which is used to define a scalable box model layout.

1. What Is Flexbox In CSS3.

  1. The Flexbox is a layout module, not a simple property, it contains parent and child elements.
  2. The main purpose of this layout is that the elements can be changed to fit the available space of parent.
  3. When the available space gets larger, the Flex element will stretch to fill the available space. It will also automatically shrink when the Flex element goes beyond the available space
  4. In short, the Flex element has ability to automatically scale your layout based on browser size changes.

2. Add Flexbox Layout Library In Android Project.

Before you can use FlexboxLayout, you need to add felxbox library in android project build.gradle file as below.

  1. Change to Project mode in android studio left panel, double click build.gradle file to open it.
    change android min sdk version in build.gradle
  2. In the right panel, add below code in dependencies section.  If you find the Sync Now link in the top right corner, click it to make the new settings take effect.
    compile 'com.google.android:flexbox:0.3.0'

    Please Note : The flexbox version must be 0.3.0 or higher, smaller version do not support FlexboxLayoutMananger.
    add android flexbox library 0.3.0 and click sync now link to apply

  3. When the sync operation complete, you can use Flexbox Layout in your android app now.

3. Use FlexboxLayout In Layout XML File Example.

FlexboxLayout xml tag is similar to LinearLayout, RelativeLayout and other built-in layout. The main difference is the tag attribute.

Please refer https://github.com/google/flexbox-layout to see detail FlexboxLayout attributes explanation.

This example is simply use FlexboxLayout to wrap several TextView, you can change the attribute value to see different effect.

android use flexboxlayout in layout file outlook

Flexbox Layout Xml File.

activity_flexbox_layout.xml

<com.google.android.flexbox.FlexboxLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:flexDirection="row_reverse"
    app:justifyContent="center"
    app:alignItems="center"
    app:flexWrap="wrap">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:background="@drawable/flexbox_item_background"
        android:text="Android"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:background="@drawable/flexbox_item_background"
        android:text="iOS"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:background="@drawable/flexbox_item_background"
        android:text="Windows"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:background="@drawable/flexbox_item_background"
        android:text="Linux"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:background="@drawable/flexbox_item_background"
        android:text="Unix"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:background="@drawable/flexbox_item_background"
        android:text="MaxOS"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:background="@drawable/flexbox_item_background"
        android:text="Java"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:background="@drawable/flexbox_item_background"
        android:text="C++"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:background="@drawable/flexbox_item_background"
        android:text="Python"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:background="@drawable/flexbox_item_background"
        android:text="Kotlin"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:background="@drawable/flexbox_item_background"
        android:text="Hadoop"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:background="@drawable/flexbox_item_background"
        android:text="Solr"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="5dp"
        android:background="@drawable/flexbox_item_background"
        android:text="Lucene"/>

</com.google.android.flexbox.FlexboxLayout>

flexbox_item_background.xml

This background drawable xml file is saved in app / res / drawable folder. It is used as the TextView background.

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="@android:color/holo_green_light" />

    <corners android:radius="5sp"/>

</shape>

4. Use FlexboxLayout In Java Code Example.

android use flexboxlayout in java code outlook

You need to use FlexboxLayoutMananger with RecyclerView together to make above screen effect dynamically in java code. You can read article Android RecyclerView Example to learn how to use RecyclerView.

FlexboxLayoutMananger is only supported with version 0.3.0 or above.

Main Activity Java File.

FlexboxLayoutActivity.java

package com.dev2qa.example.layout.flexbox;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;

import com.dev2qa.example.R;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;

import java.util.ArrayList;
import java.util.List;

public class FlexboxLayoutActivity extends AppCompatActivity {

    // This is the text that will be rendered in the screen.
    private String textArr[] = {"dev2qa.com", "is", "a very good", "android example website", "there are", "a lot of", "android, java examples"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flexbox_layout);

        setTitle("dev2qa.com - FlexboxLayout Example.");

        // Get the RecyclerView object.
        RecyclerView recyclerView = (RecyclerView)findViewById(R.id.flex_box_recycler_view);

        // Create the FlexboxLayoutMananger, only flexbox library version 0.3.0 or higher support.
        FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(getApplicationContext());
        // Set flex direction.
        flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);
        // Set JustifyContent.
        flexboxLayoutManager.setJustifyContent(JustifyContent.SPACE_AROUND);
        recyclerView.setLayoutManager(flexboxLayoutManager);

        // Set adapter object.
        ViewAdapter viewAdapter = new ViewAdapter(this.initViewItemDtoList());
        recyclerView.setAdapter(viewAdapter);
    }

    private List<ViewItemDTO> initViewItemDtoList()
    {
        List<ViewItemDTO> ret = new ArrayList<ViewItemDTO>();

        for(int i=0;i < this.textArr.length; i++)
        {
            ViewItemDTO itemDto = new ViewItemDTO();
            itemDto.setText(this.textArr[i]);

            ret.add(itemDto);
        }
        return ret;
    }
}

RecyclerView Adapter Java File.

ViewAdapter.java

package com.dev2qa.example.layout.flexbox;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.dev2qa.example.R;

import java.util.List;

/**
 * Created by Jerry on 12/27/2017.
 */

public class ViewAdapter extends RecyclerView.Adapter<ViewHolder> {

    private List<ViewItemDTO> itemDtoList;

    public ViewAdapter(List<ViewItemDTO> itemDtoList) {
        this.itemDtoList = itemDtoList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_flexbox_layout_recycler_view_item, parent, false);

        final TextView textItem = (TextView)itemView.findViewById(R.id.flex_box_recycler_view_text_item);
        textItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(view.getContext(), "You click text : " + textItem.getText(), Toast.LENGTH_SHORT).show();
            }
        });

        ViewHolder ret = new ViewHolder(itemView);
        return ret;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        ViewItemDTO itemDto = itemDtoList.get(position);
        // Set item image resource id.
        // holder.getImageItem().setImageResource(itemDto.getImageId());
        // Set item text.
        holder.getTextItem().setText(itemDto.getText());
    }

    @Override
    public int getItemCount() {
        int ret = 0;
        if(this.itemDtoList!=null)
        {
            ret = itemDtoList.size();
        }
        return ret;
    }
}

RecyclerView Holder Java File.

ViewHolder.java

package com.dev2qa.example.layout.flexbox;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.dev2qa.example.R;

/**
 * Created by Jerry on 12/27/2017.
 */

public class ViewHolder extends RecyclerView.ViewHolder {

    private TextView textItem;

    public ViewHolder(View itemView) {
        super(itemView);
        if(itemView!=null) {
            this.textItem = itemView.findViewById(R.id.flex_box_recycler_view_text_item);
        }
    }

    public TextView getTextItem() {
        return textItem;
    }
}

RecyclerView Data DTO Java File.

ViewItemDTO.java

package com.dev2qa.example.layout.flexbox;

/**
 * Created by Jerry on 12/27/2017.
 */

public class ViewItemDTO {

    private String text = "";

    private int imageId = 0;

    public int getImageId() {
        return imageId;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public void setImageId(int imageId) {
        this.imageId = imageId;
    }
}

Activity Layout Xml File.

activity_flexbox_layout.xml

<android.support.v7.widget.RecyclerView
    android:id="@+id/flex_box_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

RecyclerView Item Layout Xml File.

activity_flexbox_layout_recycler_view_item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/flex_box_recycler_view_text_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/flexbox_item_background"
        android:padding="8dp"
        android:layout_margin="5dp"
        android:textSize="20dp"/>

</LinearLayout>
(Visited 4,305 times, 16 visits today)
READ :   Android Gridlayout Example Programmatically

6 Comments


  1. the sample with recycler view only show the first item….whats is wrong?

    Reply

    1. It runs success in my environment, please check your code, have

      you copy all the code in your project?

      Please check the ViewAdapter.java’s getItemCount() method,

      this method return how many items this recycler view

      will display.

      Reply

      1. The same problem, but method getItemCount() return 7.
        ret = itemDtoList.size();
        Log.d(TAG, “Items: ” + Integer.toString(ret));
        Can you update your code, because it will be very useful!

        Reply

        1. I’m looking forward to hearing from you!..

          Reply

          1. Can you send me your error picture or message and your source code to my email [email protected], then maybe i can help you.


          2. try changing the height of recyclerview to wrap_content

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.