下面是我的自定义 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/