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

问题描述 投票:0回答:1

我试图将一个句子分割成单词,并将这些单词以TextViews的形式放入RelativeLayout中,但当我将layoutparams设置为TextView时,在API 23和更老的版本中并没有生效,只有当我使用LinearLayout.LayoutParams而不是RelativeLayout.LayoutParams时,才可以在API 24和更新版本中正常工作。只有当我使用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" />

enter image description here

java android xml android-relativelayout layoutparams
1个回答
1
投票

你需要为子视图创建单独的布局参数,而不是为所有子视图使用一个。在你的代码中,把它改成在Loop里面

© www.soinside.com 2019 - 2024. All rights reserved.