【问题标题】:Add view horizontaly and verticaly in LinearLayout dynamically在 LinearLayout 中动态添加视图水平和垂直
【发布时间】:2016-06-29 07:22:39
【问题描述】:

我想将动态视图添加到水平线性布局中。但我的问题是,如果水平位置没有空间,它应该自动垂直放置。

我的头像

我的预期结果

我的代码是

    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));

           }

我的“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>

【问题讨论】:

标签: android android-layout dynamic android-linearlayout


【解决方案1】:

您不能使用单个 LinearLayout 来执行此操作,因为它具有 VERTICAL 或 HORIZONTAL 方向。我建议你看看谷歌的FlexboxLayout。它是一个提供布局的库,您可以在其中实现类似的视图。您可以通过将以下行添加到您的应用级 gradle 文件来添加此库:

compile 'com.google.android:flexbox:0.1.3'

您可以将keywordL 从LinearLayout 更改为FlexboxLayout。容器布局的示例代码如下:

<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"/>

您可以根据需要更改alignContent、alignItems和flexWrap的值。虽然这应该有效,因为它对我有用。添加孩子时,您可以执行以下操作:

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);
       }

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

【讨论】:

  • 那么请接受答案,它可能对其他人有帮助。
猜你喜欢
  • 1970-01-01
  • 2013-10-07
  • 1970-01-01
  • 2015-08-04
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多