忽略左边距和右边距

忽略左边距和右边距

本文介绍了在ConstraintLayout中向视图添加约束时,忽略左边距和右边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Java中向ConstraintLayout添加一些视图.这是布局xml:

I want to add some views to a ConstraintLayout in java. This is the layout 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>

这是活动的代码:

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);
    }
}

左右约束边距(请参阅连接调用)将被忽略.我正在使用sdk的版本25.这是一个错误吗?还是我做错了什么?没有左右边距的TextView

The left and right constraints margins (see connect calls) are simply ignored. I'm using version 25 of sdk.Is this a bug? Or Am I doing something wrong?The TextView without left and right margin

推荐答案

按照您的指定设置左右边距绝对可以.为什么它对我来说仍然是个谜.解决方法是,可以在TextView上显式设置边距,如下所示:

Setting left and right margins as you specify should definitely work. Why it doesn't remains a mystery to me. As a work-around, you can set the margins explicitly on the TextView as follows:

ConstraintLayout.LayoutParams params =
        new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_CONSTRAINT,
        ConstraintLayout.LayoutParams.MATCH_CONSTRAINT);
params.setMargins(8,8,8,8);
textView.setLayoutParams(params);

这篇关于在ConstraintLayout中向视图添加约束时,忽略左边距和右边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:37