11

下面是我的自定义代码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());
}

测试活动代码:

    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,但没有人给出明确的答案。有人可以帮助我吗?

4

3 回答 3

12

一个父视图可以在其子视图上多次调用 measure()。例如,父母可以用未指定的尺寸测量每个孩子一次以找出他们想要多大,然后如果所有孩子的无约束尺寸的总和太大或太小,则用实际数字再次调用 measure() (也就是说,如果孩子们在他们各自获得多少空间的问题上没有达成一致,则父母将进行干预并在第二次通过时制定规则)。正如https://developer.android.com/guide/topics/ui/how-android-draws.html所说。

于 2015-10-08T07:31:46.247 回答
0

过去,当我遇到类似的问题时,这是因为我的“onAnAction”代码应该在活动的 onCreate 中的活动类代码 AKA 中,而不是在自定义视图的类中。

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

于 2014-01-17T06:10:48.893 回答
0

你在你的问题中遗漏了什么吗?因为如果你重写 onMeasure,你必须调用 setMeasuredDimension(int, int) 否则你会得到一个 IllegalStateException。在您的问题中,您似乎没有任何例外。

于 2017-12-12T13:11:16.520 回答