以线性布局动态添加多个文本视图

时间:2019-01-15 09:13:20

标签: xml android-layout

我想在我的应用程序中动态添加多个textview。问题不在于动态添加,而在于安排它们。我需要与所附图像相同的布局。我该如何实现?enter image description here

1 个答案:

答案 0 :(得分:0)

使用flexbox布局将此依赖项添加到您的项目中

implementation 'com.google.android:flexbox:0.3.2'

并将布局添加到您的xml

 <com.google.android.flexbox.FlexboxLayout
      android:id="@+id/tagsView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      app:flexWrap="wrap"
      app:alignItems="stretch"
      app:alignContent="stretch"/>

和您的Java类

 private void setUpTags() {

    tagsCount = //... integer number of textviews
    private TextView[] tags= new TextView[tagsCount];//create dynamic textviewsarray
    LinearLayout.LayoutParams layoutParams = new 
    LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
    LinearLayout.LayoutParams.WRAP_CONTENT);

    //loop to customize the text view and add it to flex box
    for (int i = 0; i < tagsCount; i++) {

        tags[i] = new TextView(getContext());
        GradientDrawable gD = new GradientDrawable();
        int strokeWidth = 5;
        int strokeColor = getResources().getColor(R.color.strokColor);

        gD.setStroke(strokeWidth, strokeColor);
        gD.setCornerRadius(15);
        gD.setShape(GradientDrawable.RECTANGLE);

        tags[i].setBackground(gD);
        tags[i].setText("this is tag text");
        layoutParams.setMargins(10, 5, 10, 5);
        tags[i].setPadding(17, 15, 17, 15);
        tagsView.addView(tags[i], layoutParams);
    }
}