1

I want to implement a TextView, and I override the method "onMearsure()", I just make a simple Layout, activity_main, just a LinearLayout. xml like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">    </LinearLayout>

and I put my TextView into this layout by using Java code.like this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.activity_main, null);
    setContentView(root);

    KTextView textView = new KTextView(this, null);
    textView.setText("abcd");
    root.addView(textView);

}

and now, I made some Log in onMeasure() method, it show the widthMode and heightMode are EXACTLY and AT_MOST. But its parent(LinearLayout)'s width and height both are MATCH_PARENT, so I think width mode and height mode both are AT_MOST.

and I want to know who invoke TextView.onMeasure()? is its parent container?

krosshj
  • 855
  • 2
  • 11
  • 25

1 Answers1

2

Well, a frequently asked question when a developer is going to extends View.

onMeasure() is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent.

I will suggest first go through this.

I want to highlight a very specific para from this specific article.

Drawing the layout is a two pass process: a measure pass and a layout pass. The measuring pass is implemented in measure(int, int) and is a top-down traversal of the View tree. Each View pushes dimension specifications down the tree during the recursion. At the end of the measure pass, every View has stored its measurements. The second pass happens in layout(int, int, int, int) and is also top-down. During this pass each parent is responsible for positioning all of its children using the sizes computed in the measure pass.

After reading this it is very easy to understand that whenever your layout is visible on screen. It will from root node (means parent to child) and whenever your view is going to draw it will check available space and trigger onMeasure with required specification. I think this answer will help.

Sorry, forget to answer your question after going through the source code of LinearLayout you will find a private method:

private void forceUniformWidth(int count, int heightMeasureSpec) {
      ...
}

which will force your widthmode to EXACTLY. See 509 line in this code.

Community
  • 1
  • 1
Chirag Jain
  • 1,612
  • 13
  • 20