android - 如何以编程方式创建垂直或水平指南

标签 android android-layout android-constraintlayout

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

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

  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

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

最佳答案

您收到错误是因为未设置方向。但是,这只是您的代码中存在的一个问题。这是 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;
    }
}

关于android - 如何以编程方式创建垂直或水平指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56021360/

相关文章:

android - 为什么要选择约束布局,因为我们已经有了相对布局?

android ConstraintLayout 流程 : align items from right to left

java - 从字符串数组中获取特定项目

android - 服务 vs IntentService 在位置跟踪服务的情况下

当我尝试更改选项卡时,android模拟器不断崩溃

android - 我在哪里可以找到一些好的 Android UI 示例?

android - 使用 match_parent 和 0dp 作为宽度时,具有 0dp 高度的 ConstraintLayout View 具有不同的实际高度

Android Fragment Xml 使用样式出现 fatal error

android - 删除 AppBarLayout 小部件 android 下方的阴影

android - 如何在点击它时获得 EditText 的值(value)?