gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 18:31:31 25 4
gpt4 key购买 nike

我需要以编程方式创建指南,并将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com