2

I need to add TextViews to a Layout (RelativeLayout or LinearLayout I don't care) programatically.

I want something like this:

enter image description here

After the textview 4 there is no more space on the right side so the next TextView will be placed in a new Line bellow.

This is what I have done:

Create a LinearLayout in the xml file:

<LinearLayout
    android:id="@+id/my_linear_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
</LinearLayout>

In my code, I loop over a list of Objects and add a new TextView for each objekt:

LinearLayout myLinearLayout = (LinearLayout) itemView.findViewById(R.id.my_linear_layout);

for(MyObject object : myObjectList) {
          final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
          params.setMargins(20, 0, 20, 0); // llp.setMargins(left, top, right, bottom);

          final TextView textView = new TextView(context);
          textView.setText(object.getName());
          textView.setLayoutParams(params);

          myLinearLayout.addView(textView, params);
}

But this is the result I get:

enter image description here

I have thought adding LinearLayouts vertically instead of TextViews, but still my problem is that I don't know when I need to add the next the next one, I mean, when there is no more space on the right side.

I have also tried it with TableLayout but still the same problem, I don't know when I have to add the next row.

Any ideas? Maybe there is a View that already solves that problem and I don't know...

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ale
  • 2,282
  • 5
  • 38
  • 67
  • 1
    Yes, I have just implemented in my app. You have create Custom ViewGroup something called FlowLayout. – Vinodh Dec 08 '16 at 15:04
  • 1
    http://stackoverflow.com/questions/4474237/how-can-i-do-something-like-a-flowlayout-in-android – Vinodh Dec 08 '16 at 15:05
  • Thanks! that's exactly what I wanted. I did'n even know that this was possible, thanks! – Ale Dec 08 '16 at 16:54
  • 1
    Flexbox Layout may help you here: https://github.com/google/flexbox-layout – Harry Dec 12 '18 at 04:32

0 Answers0