Android ConstraintLayout:如何在另一个下面添加动态视图

sku*_*sku 5 android android-layout android-constraintlayout

我试图在运行时在Constraint布局中将TextViews添加到另一个下面.但我总是只得到一个textview,其余的隐藏在它背后.我尝试了几种方法,包括链接视图,但似乎没有任何效果.

private void method(int position)
    {
        ConstraintSet set = new ConstraintSet();
        TextView textView = new TextView(getContext());
        int textViewId = 100 + position;
        //previousTextViewId = textViewId;
        textView.setId(textViewId);
        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(0, WRAP_CONTENT);
        layoutParams.rightToRight = PARENT_ID;
        layoutParams.leftToLeft = guideline_60.getId(); //Vertical GuideLine of 60%
        layoutParams.rightMargin = 8;
        textView.setLayoutParams(layoutParams);
        if (Build.VERSION.SDK_INT < 23)
        {
            textView.setTextAppearance(getContext(), R.style.textStyle);
        }
        else
        {
            textView.setTextAppearance(R.style.textStyle);
        }
        textView.setBackgroundColor(backgroundColor);
        textView.setText(categoryName);
        textView.setGravity(Gravity.CENTER);
//markerLayout is the ConstraintLayout 
        markerLayout.addView(textView, position);
        set.clone(markerLayout);
        //set.addToVerticalChain(textView.getId(),previousTextViewId,PARENT_ID);
        set.connect(textView.getId(), ConstraintSet.TOP, markerLayout.getId(), ConstraintSet.TOP, 60);
        set.applyTo(markerLayout);
    }
Run Code Online (Sandbox Code Playgroud)

我期待看到这样的事情 -

在此输入图像描述

Nic*_*oso 7

您说所有textview的顶部都连接在父级的顶部:

set.connect(textView.getId(), ConstraintSet.TOP, 
        markerLayout.getId(), ConstraintSet.TOP, 60);
Run Code Online (Sandbox Code Playgroud)

你想说,一个的顶部连接到另一个的底部 - 像这样:

set.connect(textView.getId(), ConstraintSet.TOP, 
    previousTextView.getId(), ConstraintSet.BOTTOM, 60);
Run Code Online (Sandbox Code Playgroud)

你的方法叫做方法?

  • 我试图概括我的代码,因此将方法重命名为“ method” :)。我下面的代码if(position == 0){Timber.d(“ Position-” + position); set.connect(textView.getId(),ConstraintSet.TOP,markerLayout.getId(),ConstraintSet.TOP,16); } else {Timber.d(“ Position-” + position); set.connect(textView.getId(),ConstraintSet.TOP,previousTextViewId,ConstraintSet.BOTTOM,16); } (2认同)