首页 > 解决方案 > setLayoutParams() 在 API <= 23 中不起作用

问题描述

我正在尝试将句子拆分为单词并将单词作为 TextViews 放入 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
    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" />

在此处输入图像描述

标签: javaandroidxmlandroid-relativelayoutlayoutparams

解决方案


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


推荐阅读