Search code examples
javaandroiduser-interfacelayout

Line-breaking widget layout for Android


I'm trying to create an activity that presents some data to the user. The data is such that it can be divided into 'words', each being a widget, and sequence of 'words' would form the data ('sentence'?), the ViewGroup widget containing the words. As space required for all 'words' in a 'sentence' would exceed the available horizontal space on the display, I would like to wrap these 'sentences' as you would a normal piece of text.

The following code:

public class WrapTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout l = new LinearLayout(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        LinearLayout.LayoutParams mlp = new LinearLayout.LayoutParams(
                new ViewGroup.MarginLayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));
        mlp.setMargins(0, 0, 2, 0);

        for (int i = 0; i < 10; i++) {
            TextView t = new TextView(this);
            t.setText("Hello");
            t.setBackgroundColor(Color.RED);
            t.setSingleLine(true);
            l.addView(t, mlp);
        }

        setContentView(l, lp);
    }
}

yields something like the left picture, but I would want a layout presenting the same widgets like in the right one.

non-wrapping

wrapping

Is there such a layout or combination of layouts and parameters, or do I have to implement my own ViewGroup for this?


Solution

  • Since May 2016 there is new layout called FlexboxLayout from Google, which is highly configurable for purpose you want.

    FlexboxLayout is in Google GitHub repository at https://github.com/google/flexbox-layout at this moment.

    You can use it in your project by adding dependency to your build.gradle file:

    dependencies {
        implementation 'com.google.android.flexbox:flexbox:3.0.0'
    }
    

    More about FlexboxLayout usage and all the attributes you can find in repository readme or in Mark Allison articles here:

    https://blog.stylingandroid.com/flexboxlayout-part-1/

    https://blog.stylingandroid.com/flexboxlayout-part2/

    https://blog.stylingandroid.com/flexboxlayout-part-3/