TextView的高度测量问题。

最近被TextView的高度测量问题搞得好烦,最终在http://blog.csdn.net/tianlan996/article/details/50408169 这篇博客看过后才搞懂原因,其实看过这篇文章后才想起

以前看过的视频里也有提到这个问题,只是我忘了,所以才走了一大段弯路,记录一下,给自己个警醒,也希望能帮到别人把。


经过查阅资料和实验,这里推荐两种方法,这两种方法有不同的应用场景。

方法一:

int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);//-----①
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);//-----②
textView.measure(widthMeasureSpec, heightMeasureSpec); //----------------------------------------③
int height = des_content.getMeasuredHeight();//获取高度

 
 
注:View.MeasureSpec.makeMeasureSpec是制定测量规则,makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);表示大小不指定,由系统自身决定测量大小。上述①、②、③句等同于:textView.measure(0, 0);
另外较常用的两种规则:
 
 
int heightMeasureSpec = MeasureSpec.
        makeMeasureSpec(1000, MeasureSpec.AT_MOST);//AT_MOST表示最大值,但这里会获取到1000像素的高度
int widthMeasureSpec = .MeasureSpec.
        makeMeasureSpec(width, MeasureSpec.EXACTLY);//精确获取值

方法二、
 
 
ViewTreeObserver observer = textView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
	textView.getViewTreeObserver().removeGlobalOnLayoutListener(this);//避免重复监听
height = textView.getMeasuredHeight();//获文本高度
//获取高度后要进行的操作就在这里执行,在外面可能onGlobalLayout还没有执行而获取不到height
         des_layout.setOnClickListener(new MyClickListner());//设置监听(其中用到了height值)
    }});

注:对于TextView,假设有如下两行文本:
String text1 = "hello what's your name, how are you. I'm  fine.";
 
 
String text2 = "hello\nhello";
其中text1宽度大于手机屏幕宽度(手机上多行显示),text2中手机上显示为两行,使用方法一测量文本控件高度,text1的结果只能得到一行的高度(非视觉高度,尽管显示为多行),text2的结果得到两行的高度。方法二得到的高度为手机上显示的高度(视觉高度);



方法三:
view.post(new runable(){run()})在run()中去测量宽高,这样的好处是view post的这个runable会在
view layout完毕之后消息队列才会去处理这个runable,这时候因为view已经layout完毕了,所以测量出来的值也是最准确的值。


猜你喜欢

转载自blog.csdn.net/tinderliang/article/details/53740102
今日推荐