Android TextView has height and width of 0

后端 未结 4 1320
野性不改
野性不改 2020-12-08 02:33

I have a small project where I want to reuse a certain UI component a few time so I created a widget by expanding a ViewGroup. In that ViewGroup I inflated a view that conta

相关标签:
4条回答
  • 2020-12-08 03:13

    Remember:getHeight() and getWidth()return 0 if components are not drawn yet.


    To find the width And height of a View before it being drawn:

    1. First call measure

      view.measure(MeasureSpec.UNSPECIFIED,MeasureSpec.UNSPECIFIED)
      
    2. Now you can get width using getMeasuredWidth and height using getMeasuredHeight

      int width = view.getMeasuredWidth();
      int height = view.getMeasuredHeight();
      

    I have posted some more ideas here: How to get width/height of a View

    0 讨论(0)
  • 2020-12-08 03:20

    So, I put a bounty on this one, and here is what I've found.

    Inflating with a null reference is A Bad Idea(TM). Essentially, that View won't get the proper layout parameters it needs (its parent sets a whole bunch of them, with a whole bunch of magic/logic involved). So inflating into null means no parents, and no inherited layout parameters. One can manually set a number of these parameters, but due to the magic involved it might not solve your problem.

    The "solution(s)" that I've come up with involve; using include (when you know how many you need) and pulling them into code, or inflating to a parent (when you need true dynamic, N things). And of course, the XML you inflate will have ID collisions, so I go about it by grabbing the last child (e.g. getChildAt(getChildCount()-1) ) of whatever I'm looking for, etc.

    0 讨论(0)
  • 2020-12-08 03:20

    Did you try passing yourself as the root:

    View.inflate(context, R.layout.xml, this); 
    

    Since you will be the parent of this View that complies with the javadoc spec.

    0 讨论(0)
  • 2020-12-08 03:27

    1) Here is some links to use Hierarchy Viewer on your dev phone.

    http://developer.android.com/guide/developing/debugging/debugging-ui.html

    and the class you'll need:

    http://github.com/romainguy/ViewServer

    2) You can also reuse layout like a component with the include tag:

    <include android:id="@+id/your_id" layout="@layout/layout_name" />
    
    0 讨论(0)
提交回复
热议问题