How to inflate XML-Layout-File correctly inside Custom ViewGroup?

后端 未结 6 1668
悲&欢浪女
悲&欢浪女 2020-12-07 16:13

I want to inflate a XML-Layout-File in a custom ViewGroup Class, my Problem is that it produces just a empty screen. Doing the same in the Activity Class works fine. Here i

6条回答
  •  孤城傲影
    2020-12-07 17:05

    I come across the same question and answer my version in Kotlin:

    You can add your customise views by xml or code. The difference is the constructor.

    YourView.kt

    class YourView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {
    
        init {
            LayoutInflater.from(context).inflate(R.layout.your_view, this, true)
         orientation = HORIZONTAL
        }
    }
    

    If you want to create your layout from code then just use:

    class YourView(context: Context) : LinearLayout(context)
    

    your_view.xml

    
    
    
            
    
            

    What's the here for?

    If you use YourView in the layout like:

     
       
       
    
    

    Then the actual view hierarchy is:

    with

       
           
          
       
    

    without (You need to use ViewGroup like )

      
           < LinearLayout >
               
              
           
        
    

提交回复
热议问题