ViewGroup finish inflate event

孤人 提交于 2019-11-28 10:10:52

If I understand your requirements correctly, an OnGlobalLayoutListener may give you what you need.

  View myView=findViewById(R.id.myView);
  myView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //At this point the layout is complete and the 
                //dimensions of myView and any child views are known.
            }
        });

Usually when creating a custom layout extending View or ViewGroup, you have to override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) and protected void onLayout(boolean changed, int left, int top, int right, int bottom). These are called during the process of inflation in order to obtain the size and location information related to the view. Also, subsequently, if you are extending ViewGroup you are to call measure(int widthMeasureSpec, int heightMeasureSpec) and layout(int l, int t, int r, int b) on every child view contained within. (measure() is called in onMeasure() and layout() is called in onLayout()).

Anyway, in onMeasure(), you generally do something like this.

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
   // Gather this view's specs that were passed to it
   int widthMode = MeasureSpec.getMode(widthMeasureSpec);
   int widthSize = MeasureSpec.getSize(widthMeasureSpec);
   int heightMode = MeasureSpec.getMode(heightMeasureSpec);
   int heightSize = MeasureSpec.getSize(heightMeasureSpec);

   int chosenWidth = DEFAULT_WIDTH;
   int chosenHeight = DEFAULT_HEIGHT;
   if(widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.EXACTLY)
      chosenWidth = widthSize;
   if(heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.EXACTLY)
      chosenHeight = heightSize;

   setMeasuredDimension(chosenWidth, chosenHeight);

   *** NOW YOU KNOW THE DIMENSIONS OF THE LAYOUT ***
}

In onLayout() you get the actual pixel coordinates of the View, so you can get the physical size like so:

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom)
{
   // Android coordinate system starts from the top-left
   int width = right - left;
   int height = bottom - top;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!