我想在 java 中向 ConstraintLayout
添加一些 View 。这是布局 xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/constraint_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.constraint.ConstraintLayout>
这是 Activity 的代码:
public class MainActivity extends AppCompatActivity {
private ConstraintLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (ConstraintLayout) findViewById(R.id.constraint_layout);
TextView textView = new TextView(this);
textView.setId(View.generateViewId());
textView.setBackgroundColor(Color.RED);
textView.setText("ciao");
layout.addView(textView);
ConstraintSet constraints = new ConstraintSet();
constraints.clone(layout);
constraints.constrainWidth(textView.getId(), ConstraintSet.MATCH_CONSTRAINT);
constraints.constrainHeight(textView.getId(), ConstraintSet.MATCH_CONSTRAINT);
constraints.setDimensionRatio(textView.getId(), "h,1:1");
constraints.connect(textView.getId(), ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, 8);
constraints.connect(textView.getId(), ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 8);
constraints.connect(textView.getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP, 8);
constraints.applyTo(layout);
}
}
左右约束边距(请参阅连接调用)被简单地忽略。我正在使用 25 版的 sdk。 这是一个错误吗?或者我做错了什么? The TextView without left and right margin
最佳答案
按照您指定的方式设置左右边距绝对有效。为什么它不对我来说仍然是个谜。作为变通方法,您可以在 TextView
上显式设置边距,如下所示:
ConstraintLayout.LayoutParams params =
new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_CONSTRAINT,
ConstraintLayout.LayoutParams.MATCH_CONSTRAINT);
params.setMargins(8,8,8,8);
textView.setLayoutParams(params);
关于android - 在 ConstraintLayout 中向 View 添加约束会忽略左右边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44129278/