1. 程式人生 > >Android約束佈局ConstraintLayout動態設定Id失效問題解決辦法

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