0

I am trying to split a sentence into words and put the words into a RelativeLayout as TextViews, but when I set layoutparams to TextView, doesn't take effect in API 23 and older. It works fine from API 24 and newer only if I use LinearLayout.LayoutParams instead of RelativeLayout.LayoutParams.

This is my split method:

public void splitWords(){

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

int size = 0;
int bgId = 0;

leftM = convertToDp(5);

String [] splitSentence = sentence.split(" ");

size = splitSentence.length;
bgId = R.drawable.word_bg;

for (int i = 0;i < size;i++){

    final TextView word = new TextView(this);

    word.setText(splitSentence[i]);

    word.setBackgroundResource(bgId);

    word.measure(0, 0);

    int butonWidth = word.getMeasuredWidth();

    if(width - convertToDp(60) - leftM <= butonWidth){
        leftM = convertToDp(5);
        topM += butonWidth + 5;
    }

    params.leftMargin = leftM + 2;
    params.topMargin = topM;

    word.setLayoutParams(params);

    leftM += butonWidth;

    wordsContainer.addView(word);
}

wordsContainer.setGravity(Gravity.CENTER); }

And this is my RelativeLayout:

    <RelativeLayout
    android:id="@+id/wordsContainer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_marginLeft="2dp"
    android:layout_marginTop="20dp"
    android:layout_marginRight="2dp"
    android:background="@drawable/white_bg_no_border"
    android:elevation="2dp"
    android:orientation="vertical"
    android:paddingLeft="20dp"
    android:paddingTop="30dp"
    android:paddingRight="20dp"
    android:paddingBottom="50dp" />

enter image description here

Besart
  • 309
  • 1
  • 4
  • 22
  • Did you try to using separate LayoutParams for each TextView, I mean create LayoutParams inside Loop and no need call measure(0,0) it will be done when you addView to container. – Công Hải May 07 '20 at 11:16
  • I need check documents about it but best practice each view should has layout params not using same for all view – Công Hải May 07 '20 at 12:19

1 Answers1

1

You need create separate layout params for child view instead of using one for all. In your code change it to inside Loop

Công Hải
  • 4,961
  • 3
  • 14
  • 20