如何通过编程创建垂直或水平的指南线

7
我需要以编程方式创建指南,并将视图应用于这些指南。
我使用了下面的代码,但它崩溃了。
  Guideline guideline = new Guideline(this);
  guideline.setId(guideline.generateViewId());
  constraintLayout.addView(guideline);


//Connecting view with the guideline


        ConstraintSet set = new ConstraintSet();
        set.connect(textView.getId(), ConstraintSet.RIGHT,   guideline.getId(), ConstraintSet.LEFT);
        set.applyTo(constraintLayout);

但是我得到了以下错误信息。

java.lang.AssertionError: LEFT(左侧)

我也不明白如何将方向应用于我创建的指南线。

1个回答

7

您遇到此错误是因为未设置方向。但这只是您代码中的一个问题。这是我在ConstraintLayout中发现有点混乱的地方之一。以下是我了解如何通过编程方式构建指南线的方法。请参见代码中的注释以获取说明。

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ConstraintLayout constraintLayout = findViewById(R.id.layout);

        // Create our guideline and add it to the layout.
        Guideline guideline = getNewGuideline(this, ConstraintLayout.LayoutParams.VERTICAL);
        constraintLayout.addView(guideline);
        // Once the view is added to the layout, we can set its position.
        guideline.setGuidelinePercent(0.25f);

        ConstraintSet set = new ConstraintSet();
        // The layout has a ConstraintSet already, so we have to get a clone of it to manipulate.
        set.clone(constraintLayout);
        // Now we can make the connections. All of our views and their ids are available in the
        // ConstraintSet.
        TextView textView = findViewById(R.id.textView);
        set.connect(textView.getId(), ConstraintSet.START, guideline.getId(), ConstraintSet.END);
        set.applyTo(constraintLayout);
    }

    private Guideline getNewGuideline(Context context, int orientation) {
        Guideline guideline = new Guideline(context);
        guideline.setId(Guideline.generateViewId());
        ConstraintLayout.LayoutParams lp =
                new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,
                        ConstraintLayout.LayoutParams.WRAP_CONTENT);
        lp.orientation = orientation;
        guideline.setLayoutParams(lp);

        return guideline;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接