以编程方式在 LinearLayout 的下一行中添加图像 - Android

Add Image in next line in LinearLayout Programatcally - Android

我有一个水平方向的 LinearLayout,但是当它在一行中跨越 4 个元素时,它会一直水平添加,我希望它自动更改到下一行,示例:

发生了什么:

我想要的:

我的代码:

btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            countLikesAdd++;
            removeMessageOrShow();
            ImageView iconLike = new ImageView(Register30.this);
            iconLike.setImageDrawable(getDrawable(R.drawable.musicicon));
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(140,130);
            lp.setMargins(5,5,5,5);
            iconLike.setLayoutParams(lp);
            relativeLayout.addView(iconLike);
        }
    });

我的XML:

<ScrollView
    android:id="@+id/svLikes"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginBottom="60dp"
    android:layout_marginEnd="14dp"
    android:layout_marginStart="14dp"
    android:layout_marginTop="48dp"
    android:background="#2f3342"
    android:orientation="vertical"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="@+id/btnAdd"
    app:layout_constraintVertical_bias="0.0"
    tools:layout_constraintBottom_creator="1"
    tools:layout_constraintLeft_creator="1"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintTop_creator="1">
    <LinearLayout
        android:id="@+id/linearLayout"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp"
        android:paddingEnd="5dp"
        android:paddingTop="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        >
    </LinearLayout>
</ScrollView>

LinearLayout 不支持在不合适的情况下换行到下一行的概念。

对于少量固定项,最好的解决方案可能是在进行 google 搜索时使用可用的众多 "FlowLayout" 库之一。

对于大量项目(或您在设计时不知道的项目),您可以使用 RecyclerViewGridLayoutManager