创建以编程方式包含ConstraintLayout的多个LinearLayout?

时间:2018-08-23 21:36:53

标签: java android android-layout android-studio android-xml

我想创建一个事物列表。显然,只有一个包含ConstraintLayout的LinearLayout,我想复制LinearLayout,因为如果我不将LinearLayout用作ConstraintLayout的父代,则组件会重叠。我想将LinearLayout用作一行,将ConstraintLayout用作包含组件的区域。

总而言之,我想创建LinearLayout而不是仅仅创建ConstraintLayout。现在,我只能在LinearLayout中创建ConstraintLayout。我只想创建每个循环都包含ConstraintLayout的LinearLayout。

我的XML代码在这里:

<LinearLayout
            android:id="@+id/ParentLinearLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <android.support.constraint.ConstraintLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/ContainerConstraintLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginStart="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginTop="15dp"
                android:paddingBottom="25dp" >

            </android.support.constraint.ConstraintLayout>
        </LinearLayout>

我的Java代码在这里:

public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState){
    ConstraintLayout constraintLayout = Objects.requireNonNull(getView()).findViewById(R.id.ContainerConstraintLayout);
    TextView[] title_textview = new TextView[5];
    CircleImageView circle_images[] = new CircleImageView[10];

    for(int i = 0; i < 5; i++){
        circle_images[i] = new CircleImageView(thiscontext);
        circle_images[i].setId(View.generateViewId());
        circle_images[i].setBackgroundResource(R.drawable.waiter);
        circle_images[i].setPadding(10, 10, 10, 10);
        circle_images[i].setLayoutParams(new ConstraintLayout.LayoutParams(100, 100));
        constraintLayout.addView(circle_images[i]);

        title_textview[i] = new TextView(thiscontext);
        title_textview[i].setId(View.generateViewId());
        title_textview[i].setText("Title: " + i);
        title_textview[i].setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        constraintLayout.addView(title_textview[i]);
        ConstraintSet constraintSet = new ConstraintSet();
        constraintSet.clone(constraintLayout);
        constraintSet.connect(title_textview[i].getId(), ConstraintSet.TOP, constraintLayout.getId(), ConstraintSet.TOP);
        constraintSet.connect(title_textview[i].getId(), ConstraintSet.END, constraintLayout.getId(), ConstraintSet.END);
        constraintSet.applyTo(constraintLayout);
    }
}

0 个答案:

没有答案