How to lay out Views in RelativeLayout programmatically?

前端 未结 9 1675
心在旅途
心在旅途 2020-11-22 15:04

I\'m trying to achieve the following programmatically (rather than declaratively via XML):


   

        
9条回答
  •  情歌与酒
    2020-11-22 15:40

    Cut the long story short: With relative layout you position elements inside the layout.

    1. create a new RelativeLayout.LayoutParams

      RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(...)
      

      (whatever... fill parent or wrap content, absolute numbers if you must, or reference to an XML resource)

    2. Add rules: Rules refer to the parent or to other "brothers" in the hierarchy.

      lp.addRule(RelativeLayout.BELOW, someOtherView.getId())
      lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
      
    3. Just apply the layout params: The most 'healthy' way to do that is:

      parentLayout.addView(myView, lp)
      

    Watch out: Don't change layout from the layout callbacks. It is tempting to do so because this is when views get their actual sizes. However, in that case, unexpected results are expected.

提交回复
热议问题