Android约束布局ConstraintLayout动态设置Id失效问题解决办法

      当你需要在代码中动态给约束布局添加约束,而不能在xml文件中写约束的时候,你需要用到ConstraintSet这个类,谷歌给我们写的很清楚。https://developer.android.google.cn/reference/android/support/constraint/ConstraintSet.html

      但是,我在动态写约束的时候遇到一个问题,上代码

        ConstraintLayout cl = findViewById(R.id.parent_layout);
        Button b1 = new Button(this);
        Button b2 = new Button(this);
        cl.addView(b1);
        cl.addView(b2);
        b1.setId(View.generateViewId());
        b2.setId(View.generateViewId());
        ConstraintSet set = new ConstraintSet();
        set.clone(cl);
        set.connect(b1.getId(), ConstraintSet.TOP, b2.getId(), ConstraintSet.BOTTOM);
        set.applyTo(cl);

我发现失效,b1并没有按照我想要的放在b2下面。由于种种努力,最后终于找到解决方法。Id的设置必须要在addView之前,如果先addView然后再设置id就会失效,不知道是不是约束布局的bug,但是相对布局就没有问题。所以解决方案就是在addView之前设置id即可。

        ConstraintLayout cl = findViewById(R.id.parent_layout);
        Button b1 = new Button(this);
        Button b2 = new Button(this);
        b1.setId(View.generateViewId());
        b2.setId(View.generateViewId());
        cl.addView(b1);
        cl.addView(b2);
        ConstraintSet set = new ConstraintSet();
        set.clone(cl);
        set.connect(b1.getId(), ConstraintSet.TOP, b2.getId(), ConstraintSet.BOTTOM);
        set.applyTo(cl);

你可能感兴趣的:(Android提升)