Android的TextView中具有的高度和宽度0有的、宽度、高度、Android

由网友(离癸)分享简介:我有一个小的项目,我想重复使用某个UI组件的几个时间,所以我通过扩张的ViewGroup创建一个小部件。在此我的ViewGroup充气包含一个TextView一个的LinearLayout内并补充说,膨胀欣赏到的ViewGroup槽addView景色。外的LinearLayout扩大自身完美,但内部的TextView拥...

我有一个小的项目,我想重复使用某个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 的如果组件尚未领取的

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

第一次调用测量

  view.measure(MeasureSpec.UNSPECIFIED,MeasureSpec.UNSPECIFIED)
 
android中自动适应宽度的TextView

现在,您可以使用 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:

First call measure

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

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

阅读全文

相关推荐

最新文章