Android Constraint Layout Programmatically?

后端 未结 2 677
耶瑟儿~
耶瑟儿~ 2020-12-13 17:43

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:



        
相关标签:
2条回答
  • 2020-12-13 18:12

    I ran into the exact same dilemma coming from iOS where I feel like building views programatically is a more common practice.

    I am actually porting the Stevia library to android with Kotlin here, since the new ConstraintLayout is quite similar to our beloved Autolayout.

    Here is how you define a simple view

    class MyView(context: Context): ConstraintLayout(context) {
    
      val label = TextView(context)
    
      init {
    
          // View Hierarchy
          subviews(
              label
          )
    
          // Layout
          label.centerInParent()
    
          // Style
          label.style {
              textSize = 12F
          }
      }}
    

    Be aware that this is Pure native Constraint layout under the hood, as explained by Martin's answer.

    It's only the beginning but it has proven to be a delightful way to write android views in Kotlin so far so I thought I'd share. Hope this helps :)

    0 讨论(0)
  • 2020-12-13 18:14

    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/android/support/constraint/ConstraintLayout.LayoutParams.html

    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);
    
    0 讨论(0)
提交回复
热议问题