如何以编程方式创建垂直或水平参考线

dev*_*v90 4 android android-layout android-constraintlayout

我需要以编程方式创建指南,并将视图应用于这些指南。

我使用了以下代码,但它崩溃了。

  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);
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误消息。

java.lang.AssertionError: 左

我也无法理解如何将方向应用于我创建的指南

Che*_*amp 5

您收到错误是因为未设置方向。但是,这只是您的代码中存在的一个问题。这是ConstraintLayout 的一个领域,我觉得有点模糊。这是我如何理解以编程方式构建指南。有关解释,请参阅代码中的注释。

主活动.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;
    }
}
Run Code Online (Sandbox Code Playgroud)