Why is onMeasure () called twice in my regular view?

Below is my code for my custom View :

XML layout:

 <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> 

Code in my CustomView.java :

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

Test Activity Code:

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

logcat output:

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

I was looking for StackOverflow, but no one gave a clear answer. Can someone help me?

+8
android android-custom-view
source share
3 answers

A parent view can call a measure () more than once on its children. For example, a parent can measure each child once with indefinite measurements to find out how large they are, and then call measure () again with real numbers if the sum of all child unlimited sizes is too large or too small (that is, if the children do not agree among themselves regarding how much space they get, the parent will intervene and set the rules on the second pass). as https://developer.android.com/guide/topics/ui/how-android-draws.html says.

+9
source share

In the past, when I had problems like this, and because my β€œonAnAction” code had to be inside the AKA activity class code in onCreate for activity, and not in the user view class.

It might work, but no guarantees. It usually takes some agility and understanding of the Android life cycle.

0
source share

Are you missing something in your question? Because if you override onMeasure, you must call setMeasuredDimension (int, int), otherwise you will get an IllegalStateException. In your question, you do not seem to get any exceptions.

0
source share

All Articles