Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

Android Constraint Layout Programmatically?

In iOS I'm a big fan of deleting the storyboard and using the Cartography framework to lay everything out in code. This is stolen from Cartography's github:

constrain(view1, view2) { view1, view2 in
    view1.width   == (view1.superview!.width - 50) * 0.5
    view2.width   == view1.width - 50
    view1.height  == 40
    view2.height  == view1.height
    view1.centerX == view1.superview!.centerX
    view2.centerX == view1.centerX

    view1.top >= view1.superview!.top + 20
    view2.top == view1.bottom + 20
}

Is there any equivalent at all for Android? It seems like the new Constraint Layout is a step in the right direction but I would like to do it programmatically.

question from:https://stackoverflow.com/questions/39296627/android-constraint-layout-programmatically

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A little late to the game, but you need to basically treat your views in a constraint layout as regular views that simply have their own LayoutParams.

In the ConstraintLayout case, the documentation is located here: https://developer.android.com/reference/androidx/constraintlayout/widget/ConstraintLayout.LayoutParams

This class contains the different attributes specifying how a view want to be laid out inside a ConstraintLayout. For building up constraints at run time, using ConstraintSet is recommended.

So, the recommended method is to use a ConstraintSet.

There's a nice code sample there, but the core concept is you need to create a new set (by copying/cloning/new, etc), set its properties, and then apply it to your layout.

E.g.: Suppose your layout contains a ConstraintLayout (called mConstraintLayout here) and inside it contains a view (R.id.go_button in the sample), you could do:

    ConstraintSet set = new ConstraintSet();

    // You may want (optional) to start with the existing constraint,
    // so uncomment this.
    // set.clone(mConstraintLayout); 

    // Resize to 100dp
    set.constrainHeight(R.id.go_button, (int)(100 * density));
    set.constrainWidth(R.id.go_button, (int)(100 * density));

    // center horizontally in the container
    set.centerHorizontally(R.id.go_button, R.id.rootLayout);

    // pin to the bottom of the container
    set.connect(R.id.go_button, BOTTOM, R.id.rootLayout, BOTTOM, 8);

    // Apply the changes
    set.applyTo(mConstraintLayout); 
    // this is my… (ConstraintLayout) findViewById(R.id.rootLayout);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...