When CustomView extens ConstraintLayout and use ConstraintSet in constructor, the constraint not work

Viewed 72

As the title, my CustomView extend ConstraintLayout, when set constraint use ConstraintSet in constructor, it not work. i try to postDelayed constraint, it work!

Is there a Function to put constraint ?

    public  class ConstraintAfterInit extends ConstraintLayout{
        LinearLayout view;
        public ConstraintAfterInit(@NonNull Context context) {
            super(context);

            view = new LinearLayout(context);
            view.setId(View.generateViewId());
            view.setBackgroundColor(Color.GREEN);
            ConstraintLayout.LayoutParams viewLp = new ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
            viewLp.matchConstraintMinHeight = 200;
            view.setLayoutParams(viewLp);
            this.addView(view);
            //layout()

            this.postDelayed(new Runnable() {
                @Override
                public void run() {
                    layout();
                }
            },2000);

        }

        public void layout(){
            ConstraintLayout contain = this;
            ConstraintSet viewSet = new ConstraintSet();
            viewSet.clone(contain);
            viewSet.connect(view.getId(),ConstraintSet.LEFT,contain.getId(),ConstraintSet.LEFT,20);
            viewSet.connect(view.getId(),ConstraintSet.RIGHT,contain.getId(),ConstraintSet.RIGHT,20);
            viewSet.connect(view.getId(),ConstraintSet.TOP,contain.getId(),ConstraintSet.TOP,20);
            viewSet.connect(view.getId(),ConstraintSet.BOTTOM,contain.getId(),ConstraintSet.BOTTOM,20);
            viewSet.applyTo(contain);
        }
    }

The Result: screenshot

1 Answers

I got the answer from issueTracker of google, we can creat status tag "new" on constructor, then use it in onAttachToWindow

Related