Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java setLayoutParams()在API中不工作_Java_Android_Xml_Android Relativelayout_Layoutparams - Fatal编程技术网

Java setLayoutParams()在API中不工作

Java setLayoutParams()在API中不工作,java,android,xml,android-relativelayout,layoutparams,Java,Android,Xml,Android Relativelayout,Layoutparams,我试图将一个句子拆分为单词,并将单词作为TextView放入RelativeLayout中,但当我将layoutparams设置为TextView时,在API 23及更早版本中不会生效。仅当我使用LinearLayout.LayoutParams而不是RelativeLayout.LayoutParams时,它在API 24和更新版本中工作正常 这是我的拆分方法: public void splitWords(){ RelativeLayout.LayoutParams params = ne

我试图将一个句子拆分为单词,并将单词作为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);
}
words container.setGravityGravity.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" />

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

您是否尝试为每个TextView使用单独的LayoutParams,我的意思是在循环内部创建LayoutParams,无需调用measure0,0。将视图添加到容器时将完成此操作。我需要检查有关它的文档,但最佳做法是每个视图都应具有布局参数,而不是对所有视图使用相同的布局参数