How to lay out Views in RelativeLayout programmatically?

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

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


   

        
9条回答
  •  失恋的感觉
    2020-11-22 15:35

    If you really want to layout manually, i'd suggest not to use a standard layout at all. Do it all on your own, here a kotlin example:

    class ProgrammaticalLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ViewGroup(context, attrs, defStyleAttr) { 
        private val firstTextView = TextView(context).apply {
            test = "First Text"
        }
    
        private val secondTextView = TextView(context).apply {
            text = "Second Text"
        }
    
        init {
            addView(firstTextView)
            addView(secondTextView)
        }
    
        override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
            // center the views verticaly and horizontaly
            val firstTextLeft = (measuredWidth - firstTextView.measuredWidth) / 2
            val firstTextTop = (measuredHeight - (firstTextView.measuredHeight + secondTextView.measuredHeight)) / 2
            firstTextView.layout(firstTextLeft,firstTextTop, firstTextLeft + firstTextView.measuredWidth,firstTextTop + firstTextView.measuredHeight)
    
            val secondTextLeft = (measuredWidth - secondTextView.measuredWidth) / 2
            val secondTextTop = firstTextView.bottom
            secondTextView.layout(secondTextLeft,secondTextTop, secondTextLeft + secondTextView.measuredWidth,secondTextTop + secondTextView.measuredHeight)
        }
    
        override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { 
            // just assume we`re getting measured exactly by the parent
            val measuredWidth = MeasureSpec.getSize(widthMeasureSpec)
            val measuredHeight = MeasureSpec.getSize(heightMeasureSpec)
    
            firstTextView.measures(MeasureSpec.makeMeasureSpec(meeasuredWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
            secondTextView.measures(MeasureSpec.makeMeasureSpec(meeasuredWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
    
            setMeasuredDimension(measuredWidth, measuredHeight)
        }
    }
    

    This might give you an idea how this could work

提交回复
热议问题