在水平线性布局中添加新行

f.t*_*ski 0 android android-linearlayout

我正在以水平方向的线性布局创建动态图像。我在用:

ImageView imageView = new ImageView(getContext());
            imageView.setLayoutParams(new 
android.view.ViewGroup.LayoutParams(200,200));
            imageView.setOnTouchListener(new MyTouchListener());
            imageView.setOnDragListener(new MyDragListener());
            setImageIcon(imageView, ap.getPackageName());
            topLayout.addView(imageView);
Run Code Online (Sandbox Code Playgroud)

但在屏幕的末尾,它继续在右侧无限添加图标。我想添加边框并从新行开始。有什么选项可以做到这一点吗?这是我的 xml:

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/master_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnCount="4"
        android:columnWidth="320dp"
        android:orientation="vertical"
        android:rowCount="8"
        android:stretchMode="columnWidth">

<LinearLayout
    android:id="@+id/top_layout"
    android:layout_width="match_parent"
    android:layout_height="280dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:background="@drawable/shape_droptarget_grey"
    android:gravity="left"
    android:orientation="horizontal">
    <TextView android:id="@+id/text_top"
              android:layout_width="match_parent"
              android:layout_height="40dp"
              android:clickable="false"
              android:text="Security upgrade avaliable"
              android:textAlignment="center"
              android:textSize="28dp"/>

</LinearLayout>


<LinearLayout
    android:id="@+id/bottom_layout"
    android:layout_width="match_parent"
    android:layout_height="280dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:background="@drawable/shape_droptarget_green"
    android:gravity="left"
    android:orientation="horizontal">
    <TextView android:id="@+id/text_bottom"
              android:layout_width="match_parent"
              android:layout_height="40dp"
              android:clickable="false"
              android:gravity="center"
              android:text="Secured Apps"
              android:textAlignment="center"
              android:textSize="28dp"/>

</LinearLayout>


</GridLayout>
Run Code Online (Sandbox Code Playgroud)

Rai*_*ker 5

这是线性布局无法完成​​的。如果将方向设置为水平,则永远不会换行。您可以决定布局中允许有多少视图,然后总是像这样检查,如果超过此计数,只需在下面添加另一个线性布局以模仿您的 topLayout 的新行并开始添加到新布局,但这是一种解决方法

int childCount = ((ViewGroup)linearLayout).getChildCount();
Run Code Online (Sandbox Code Playgroud)

一个更干净的解决方案是按原样使用 GridLayout。您还可以在那里动态添加图像并标记一行中的最大元素,而无需使用 LinearLyout。下面的代码意味着您将在一行中有 2 个元素,并且行数与您放置的行数相同。您可以使用add方法来添加 ImageView。

GridLayout mLayout = new GridLayout(0,2);
Run Code Online (Sandbox Code Playgroud)

另一个解决方案是 FlowLayout 的一个版本。查看这个git 示例