【问题标题】:setLayoutParams() is not working in API <= 23setLayoutParams() 在 API <= 23 中不起作用
【发布时间】:2020-08-22 15:38:21
【问题描述】:

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

【问题讨论】:

  • 您是否尝试为每个 TextView 使用单独的 LayoutParams,我的意思是在 Loop 内创建 LayoutParams 并且不需要调用 measure(0,0) 它会在您将视图添加到容器时完成。
  • 我需要检查有关它的文档,但最佳做法是每个视图的布局参数不应该对所有视图使用相同

标签: java android xml android-relativelayout layoutparams


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 2016-09-04
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多