setLayoutParams() 在 API <= 23 中不起作用

setLayoutParams() is not working in API <= 23

我试图将一个句子拆分成单词并将这些单词作为 TextView 放入 RelativeLayout 中,但是当我将 layoutparams 设置为 TextView 时,在 API 23 及更早版本中不生效。只有当我使用 LinearLayout.LayoutParams 而不是 RelativeLayout.LayoutParams.

时,它才能在 API 24 和更新版本中正常工作

这是我的拆分方法:

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); }

这是我的 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" />

您需要为子视图创建单独的布局参数,而不是为所有子视图使用一个。在您的代码中将其更改为 Loop

内部