Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android TextView has height and width of 0

Tags:

android

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 contained a TextView inside a LinearLayout and added that inflated view to the ViewGroup trough addView.

The outer LinearLayout expands itself perfectly but the inner TextView have getHeight() = 0 and getWith() = 0 when I view it through Hierarchy Viewer. The strange thing is that layout_height and layout_width is the values I gave them in my xml.

I don't have the code here but it looked something like this:

xml:

<LinearLayout       android:layout_width="fill_parent"       android:layout_height="fill_parent">        <TextView           android:text="random text.."           android:layout_with="200px"           android:layout_height="50px" />   </LinearLayout>   

Java:

class MyWidget extends ViewGroup { ...  //In constructor   myView = View.inflate(context, R.layout.xml, null);   addView(myView);    //In layout   myView.layout(l, t, r, b);   

I have tried to give my text view fill_parent values for size but it didn't help.

like image 407
MrFroYo Avatar asked Apr 28 '11 14:04

MrFroYo


People also ask

How do you find the height and width of a view?

The width and height can be obtained by calling getWidth() and getHeight().

How do you find the height of a view?

You can use the window. innerHeight property to get the viewport height, and the window. innerWidth to get its width. let viewportHeight = window.


2 Answers

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

like image 90
Sherif elKhatib Avatar answered Oct 08 '22 02:10

Sherif elKhatib


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" /> 
like image 41
plus- Avatar answered Oct 08 '22 03:10

plus-