android - 为什么在我的自定义 View 中调用了两次 onMeasure()?

标签 android android-custom-view onmeasure

下面是我的自定义 View 代码:

XML 布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.project.summary"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:background="@color/BgColor">

    <com.project.summary.customview.CustomView
        android:id="@+id/customView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:colorValue="@color/textRed"
        app:textString="This the Custom View!!!"
        app:textSize="20sp"
        />

</LinearLayout>

我的 CustomView.java 中的代码:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    Log.e("140117", "onMeasure()"+this.getHeight()+"||"+this.getWidth());
}

测试 Activity 代码:

    public class CustomViewActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.customview_layout);
    }
}

日志输出:

01-17 13:47:01.203: E/140117(11467): onMeasure()0||0
01-17 13:47:01.243: E/140117(11467): onMeasure()28||212

我搜索了 StackOverflow,但没有人给出明确的答案。有人可以帮助我吗?

最佳答案

父 View 可能会对其 subview 多次调用 measure() 。例如, parent 可以用未指定的尺寸测量每个 child 一次,以确定他们想要多大,然后如果所有 child 的无约束尺寸的总和太大或太小,则用实际数字再次调用 measure() (也就是说,如果 children 不同意他们各自获得多少空间, parent 将进行干预并在第二次通过时制定规则)。 作为https://developer.android.com/guide/topics/ui/how-android-draws.html说。

关于android - 为什么在我的自定义 View 中调用了两次 onMeasure()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21178959/

相关文章:

android - 3 个 textView 项目根据其长度换行

android - ScrollView 内的 FlowLayout

android - onMeasure 被调用 1,500 多次

Android:ListView位置和DatePicker

java - 设置 TextView 的文本时出现 NullPointerException

java - 如何在android中没有LiveData的情况下使用房间和数据库?

java - 从异步任务获取空响应,响应代码为 200,这意味着成功

android - 绘制自定义形状

Android 会根据布局定位崩溃

android - 在应用 XML 属性之前恢复 View 状态