Adding constraints to a view in a ConstraintLayout ignore left and right margins

做~自己de王妃 提交于 2019-12-22 09:28:51

问题


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>

and this is the code of the 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);
    }
}

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


回答1:


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


来源:https://stackoverflow.com/questions/44129278/adding-constraints-to-a-view-in-a-constraintlayout-ignore-left-and-right-margins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!