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

后端 未结 6 1660
悲&欢浪女
悲&欢浪女 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 16:56

    I don't know what's going on in these answers.. I think calling onLayout manually is a bit crazy.

    The LayoutInflater.inflate function is rather straight forward. If you're using the one that accepts the 3rd boolean argument (attachToRoot) and it's true, it will add the views from your XML to your parent view (the 2nd argument). If you're using the one that accepts only 2 arguments, it will pass true to attachToRoot by default if you provide a parent that isn't null.

    In any case, most of the mess you're experiencing is because the views from your XML are added to your custom view. Since your XML has a RelativeLayout root and your custom view is also a RelativeLayout - you're getting a relative layout inside a relative layout.

    This is probably not what you want.

    The answer given by Konstantin makes sense, but you're wasting a view because you're placing a RelativeLayout inside a FrameLayout. Since Android can't hold too many nested views, it's a good idea to optimize and not add this unnecessary FrameLayout.

    I suggest keeping your custom view as RelativeLayout and changing your XML root to . Then use the inflate form which adds the XML views to your parent - like View.inflate(context,int,this)

    The purpose of the tag is to skip the root node in the XML.. look it up.

提交回复
热议问题