在LinearLayout中动态添加视图horizo​​ntaly和verticaly

Mah*_*kul 3 android dynamic android-layout android-linearlayout

我想将动态视图添加到Horizo​​ntal LinearLayout中.但我的问题是如果水平没有空间,它应该自动垂直放置.

我的形象

在此输入图像描述

我的预期结果

在此输入图像描述

我的代码是

    for (int j = 0; j < jobDet.getKeywords().length; j++) {

               RelativeLayout tr_head = (RelativeLayout) getLayoutInflater().inflate(R.layout.tag_lay, null);

               TextView label_date = (TextView) tr_head.findViewById(R.id.tag_name);
               label_date.setText(jobDet.getKeywords()[j]);

               keywordL.addView(tr_head, new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT));

           }
Run Code Online (Sandbox Code Playgroud)

我的"tag_lay.xml"

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content">
         <TextView
             android:layout_width="wrap_content"
             android:layout_height="30dp"
             android:id="@+id/tag_name"
             android:paddingLeft="10dp"
             android:paddingRight="10dp"
             android:background="@drawable/round_edit_box"
             android:text="     PHP     "
             android:gravity="center"
             android:lines="1"
             android:layout_marginRight="5dp"/>

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

him*_*496 6

你不能用单身,LinearLayout因为它有VERTICALHORIZONTAL方向.我建议你看一下谷歌的FlexboxLayout.它是一个库,提供了一个可以实现类似视图的布局.您可以通过在应用程序级别gradle文件中添加以下行来添加此库:

compile 'com.google.android:flexbox:0.1.3'
Run Code Online (Sandbox Code Playgroud)

您可以更改keywordLFlexboxLayoutLinearLayout.容器布局的示例代码如下所示:

<com.google.android.flexbox.FlexboxLayout xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:app="http://schemas.android.com/apk/res-auto"
         android:id="@+id/flexbox_layout"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         app:alignContent="flex_start"
         app:alignItems="flex_start"
         app:flexWrap="wrap"/>
Run Code Online (Sandbox Code Playgroud)

您可以更改的值alignContent,alignItemsflexWrap根据您的要求.虽然这应该有用,因为它对我有用.在添加孩子时,您可以执行以下操作:

for (int j = 0; j < jobDet.getKeywords().length; j++) {

           RelativeLayout tr_head = (RelativeLayout) getLayoutInflater().inflate(R.layout.tag_lay, keywordL, false );

           TextView label_date = (TextView) tr_head.findViewById(R.id.tag_name);
           label_date.setText(jobDet.getKeywords()[j]);
           keywordL.addView(tr_head);
       }
Run Code Online (Sandbox Code Playgroud)

如果您在实施时遇到问题,请告诉我.