Android Constraint Layout Programmatically?

后端 未结 2 679
耶瑟儿~
耶瑟儿~ 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 :)

提交回复
热议问题