androidandroid-layoutlayout-inflaterandroid-flexboxlayoutlayout-optimization

Display many views efficiently in a FlexboxLayout


My goal is to efficiently display a lot of TextViews (with background) in a FlexboxLayout (or something similar).

I want to display information about actors and crew members from a movie in a kind of 'tag'-layout style

How the layout looks like (one of the FlexboxLayouts is marked)

I inflate the TextViews dynamically via LayoutInflater into a FlexboxLayout. The problem is of course that with a lot of data (which means a lot of views, sometimes 30 or more in over 20 Flexbox-Layouts) the creation time of my fragment/activity increases and the activtiy takes longer to open.

The TextView I inflate:

<TextView 
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/tag_name"
      android:layout_width="wrap_content"
      android:layout_height="30dp"
      android:layout_margin="5dp"
      android:paddingStart="10dp"
      android:paddingEnd="10dp"
      android:gravity="center_vertical"
      android:background="@drawable/bg_tag"
      android:textColor="?android:textColorSecondary"
      android:text="@string/placeholder" />

My container layout (TextViews get inflated into the FlexboxLayout @+id/fxl_names):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
  android:orientation="vertical">

  <TextView
    android:id="@+id/txt_names"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="?attr/colorOnBackground"
    android:padding="5dp"
    android:textSize="16sp"
    android:textStyle="bold"
    android:text="test" />

  //TextViews get inflated into this FlexboxLayout

  <com.google.android.flexbox.FlexboxLayout
    android:id="@+id/fxl_names"
    app:flexWrap="wrap"
    android:animateLayoutChanges="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

  <com.google.android.material.button.MaterialButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/view_more"
    android:visibility="gone"
    android:layout_margin="0dp"
    android:text="Show all"
    style="@style/Widget.MaterialComponents.Button.TextButton.Dialog" />

</LinearLayout>

Thank you for any help/advice on optimizing this layout!


Solution

  • When you had to inflate a lot of views dynamically, you should use something called ViewHolder to ensure the optimization of the inflate view action.

    For your problem may you had to use a RecyclerView instead a FlexBoxLayout, the best solution in my opinion. And a FlexBoxLayoutManager to organize your views.

    There is a example in the Android FlexBoxLayout repository