layout 如下:
<LinearLayout
android:id="@+id/layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical" >
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/info"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
我用的代码如下:
TextView title = (TextView)findViewById(R.id.title);
title.setText("ABCDE...");
title.setTextSize(20);
TextView info = (TextView)findViewById(R.id.info);
info.setText("abcde...");
info.setTextSize(16);
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
我想获取 TextView title的高度和 info,或者说layout的高度。如何实现?
我是参考别人的方法,你试试看
在onCreate函数中,View还未被展开,是无法获得高度的。
所以可以对TextvView注册一个监听者:
1.ViewTreeObserver vto = tv.getViewTreeObserver();
2. vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
3. public void onGlobalLayout() {
4.
5. heigh = appDescription.getHeight();
6.
7. tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
8. }
9. });
如下代码,既可以获取高度,还可以设置高度。
1.TextView v = (TextView) findViewById(R.id.sometext);
2.LayoutParams lp = v.getLayoutParams();
3.lp.height = 50;
4.v.setLayoutParams(lp);
你可以试试 getLineHeight() 方法。比如:
title.getLineHeight();
info.getLineHeight();
你就是回调方法没找好, 在 Activity的 onFocusChanged 回调里就OK了。
addOnGlobalLayoutListener似乎不能实时获取高度,要在显示后,如果textview在setText后必须马上知道高度怎么做?
这个方法很好,在view没有绘制的时候也有值。谢谢