Android的TextView中具有的高度和宽度0 [英] Android TextView has height and width of 0

查看:405
本文介绍了Android的TextView中具有的高度和宽度0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的项目,我想重复使用某个UI组件的几个时间,所以我通过扩张的ViewGroup创建一个小部件。在此我的ViewGroup充气包含一个TextView一个的LinearLayout内并补充说,膨胀欣赏到的ViewGroup槽addView景色。

外的LinearLayout扩大自身完美,但内部的TextView拥有的getHeight()= 0和getWith()= 0,当我通过层次结构查看器查看。但奇怪的是,layout_height和layout_width的价值观我在XML给了他们。

我没有code在这里,但它看起来是这样的:

XML:

 <的LinearLayout
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT>

    <的TextView
        机器人:文本=随机文字。
        机器人:layout_with =200px的
        机器人:layout_height =50像素/>
< / LinearLayout中>
 

Java的:

 类进myWidget扩展的ViewGroup {
...

//在构造函数中
MyView的= View.inflate(背景下,R.layout.xml,NULL);
addView(MyView的);

//在布局
myView.layout(L,T,R,B);
 

我曾试图给出大小我的文本视图FILL_PARENT值,但它并没有帮助。

解决方案
  

切记:的getHeight() getWith()返回 0 如果组件尚未领取


要找到查看正在起草前的宽度和高度:

  1. 第一次调用测量

      view.measure(MeasureSpec.UNSPECIFIED,MeasureSpec.UNSPECIFIED)
     

  2. 现在,您可以使用 getMeasuredWidth 和高度使用 getMeasuredHeight

    获得宽度

      INT宽度= view.getMeasuredWidth();
    INT高= view.getMeasuredHeight();
     


我已经发布了一些更多的想法: 如何获得宽度/高度查看

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.

解决方案

Remember:getHeight() and getWith()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: How to get width/height of a View

这篇关于Android的TextView中具有的高度和宽度0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆