为什么onMeasure()在我的自定义视图中调用了两次?

lin*_*owu 11 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>
Run Code Online (Sandbox Code Playgroud)

我的代码CustomView.java:

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

测试活动代码:

    public class CustomViewActivity extends Activity{

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

logcat输出:

01-17 13:47:01.203: E/140117(11467): onMeasure()0||0
01-17 13:47:01.243: E/140117(11467): onMeasure()28||212
Run Code Online (Sandbox Code Playgroud)

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

小智 10

父视图可以在其子项上多次调用measure().例如,父母可以用未指定的维度测量每个孩子一次以找出他们想要的大小,然后如果所有孩子的无约束大小的总和太大或太小,则用实际数字再次对他们调用measure()(也就是说,如果孩子们不同意他们每人得到多少空间,那么父母就会在第二次通过时进行干预和制定规则.如https://developer.android.com/guide/topics/ui/how-android-draws.html所说.


Der*_*rek 0

过去,当我遇到类似的麻烦时,这是因为我的“onAnAction”代码应该位于活动的类代码(AKA)的 onCreate 中,而不是位于自定义视图的类中。

这可能有效,但不能保证,通常需要一些摆弄和了解 android 生命周期。