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" />
You need create separate layout params for child view instead of using one for all. In your code change it to inside Loop