zoukankan      html  css  js  c++  java
  • 【项目笔记】拿宽高前measure(widthMeasureSpec, heightMeasureSpec)的使用技巧

    我们知道获取宽高一般写法是:

    1         view.measure(0, 0);
    2         view.getMeasuredHeight(); 

    拿宽高前什么时候可以直接用measure(0, 0);而什么时候不能用measure(0, 0);

    1.直接用measure(0, 0);

    textview控件已经存在于布局文件里,例如:

    1     <TextView
    2         android:id="@+id/textView1"
    3         android:layout_width="wrap_content"
    4         android:layout_height="wrap_content"
    5         android:text="TextView" />

    则可以直接使用measure(0, 0); 因为我们不需要去判断它的宽高模式,让系统底层自己根据布局文件判断。而什么时候不能用measure(0, 0);呢?请看第2点:

    2.不能用measure(0, 0);

    当textview控件不存在于布局文件里,也就是textview是我们用代码生生地new出来的时候,只能先确定widthMeasureSpec和heightMeasureSpec,再调用measure(widthMeasureSpec, heightMeasureSpec),而widthMeasureSpec和heightMeasureSpec可以用MeasureSpec.makeMeasureSpec(size, mode);来生成。

    例如我要一个textview,让它宽度确定(match_parent),高度不确定(wrap_content),java代码可以这么写:

     1         TextView view = new TextView(UIUtils.getContext());
     2         view.setText(getData().des);// 设置文字
     3         view.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);// 设置文字大小
     4 
     5 
     6         int widthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
     7                 MeasureSpec.EXACTLY);// 宽不变, 确定值, match_parent
     8         int heightMeasureSpec = MeasureSpec.makeMeasureSpec(2000,
     9                 MeasureSpec.AT_MOST);// 高度包裹内容, wrap_content;当包裹内容时,
    10                                         // 参1表示尺寸最大值,暂写2000, 也可以是屏幕高度
    11 
    12         // 开始测量
    13         view.measure(widthMeasureSpec, heightMeasureSpec);
  • 相关阅读:
    Hadoop启动报Error: JAVA_HOME is not set and could not be found
    mrjob在hadoop上跑的时候,报错
    Hadoop3安装踩坑 there is no HDFS_NAMENODE_USER defined. Aborting operation.
    mrjob 运行报错
    站位

    Lua基本数据类型
    常量指针和指针常量
    C基础题
    C++拷贝构造函数(深拷贝,浅拷贝)
  • 原文地址:https://www.cnblogs.com/johnsonwei/p/5674383.html
Copyright © 2011-2022 走看看