Android Flexbox Layout Example

FlexboxLayout is a google open source project. It’s aimed to implement a 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 the 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 the ability to automatically scale your layout based on browser size changes.

2. Add Flexbox Layout Library In Android Project.

  1. Before you can use FlexboxLayout, you need to add the flexbox library in the android project build.gradle file as below.
  2. Change to Project mode in the android studio left panel, double click build.gradle file to open it.
  3. In the right panel, add the below code in the dependencies section.  If you find the Sync Now link in the top right corner, click it to make the new settings take effect.
    dependencies {
    
       compile 'com.google.android:flexbox:0.3.0'
    
    }
  4. Please Note: The flexbox version must be 0.3.0 or higher, smaller versions do not support FlexboxLayoutMananger.
  5. When the sync operation is complete, you can use Flexbox Layout in your android app now.

3. Use FlexboxLayout In Layout XML File Example.

  1. FlexboxLayout XML tag is similar to LinearLayout, RelativeLayout, and other built-in layouts. The main difference is the tag attribute.
  2. Please refer to https://github.com/google/flexbox-layout to see the detailed FlexboxLayout attributes explanation.
  3. This example is simply used FlexboxLayout to wrap several TextView, you can change the attribute value to see the different effects.
    android-use-flexboxlayout-in-layout-file-outlook
  4. Below are the flexbox layout example XML file.
  5. 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>
  6. flexbox_item_background.xml: This background drawable XML file is saved in the 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

  1. You need to use FlexboxLayoutMananger with RecyclerView together to make the above screen effect dynamically in java code. You can read the article Android RecyclerView Example to learn how to use RecyclerView.
  2. FlexboxLayoutMananger is only supported with version 0.3.0 or above.
  3. 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;
        }
    }
  4. 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;
    
    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;
        }
    }
  5. 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;
    
    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;
        }
    }
  6. RecyclerView data DTO java file: ViewItemDTO.java
    package com.dev2qa.example.layout.flexbox;
    
    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;
        }
    }
  7. 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" />
  8. 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>

7 thoughts on “Android Flexbox Layout Example”

    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.

      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!

Leave a Comment

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.