android: get dimension of extended view using addOnGlobalLayoutListener but fails

泪湿孤枕 提交于 2020-01-06 15:17:31

问题


I am implementing the following addOnGlobalLayoutListener so as to measure the Extended View (doodleView) in main activity (A)'s OnCreate section.

  doodleView = (DoodleView) findViewById(R.id.doodleView);
  doodleView.setOnTouchListener(this);    

  doodleView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() 
  {
        @Override
        public void onGlobalLayout() 
        {
            doodleViewWidth = doodleView.getWidth(); 
            doodleViewHeight = doodleView.getHeight();
        }
  });

However, it underlines in red for the addOnGlobalLayoutListener with the following error statement:

The method addOnGlobalLayoutListener(ViewTreeObserver.OnGlobalLayoutListener) in the type ViewTreeObserver is not applicable for the arguments (new OnGlobalLayoutListener(){})

I have researched the web but cannot find a reason for the error. Would there be anyone knowing the problem? Many thanks in advance!


回答1:


I was doing something very similar, but then I found onMeasure. So if this is essentially a one time thing try doing something similar to this:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    View view = cardSlots[1];
    int cardHeight = view.getMeasuredHeight();
    int cardWidth = view.getMeasuredWidth();
    resizeView(playedSlot, cardWidth, cardHeight);
}

static public void resizeView(View view, int cardWidth, int cardHeight) {
    view.getLayoutParams().height = cardHeight;
    view.getLayoutParams().width = cardWidth;
    view.invalidate();
    //view.requestLayout();
    ((View)view.getParent()).invalidate();
}

This way you have less to worry about like doing this:

getViewTreeObserver().removeOnGlobalLayoutListener(this);

which you may have forgotten.




回答2:


I had the same problem. I modified the function as

doodleView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() 
  {
        @Override
        public void onGlobalLayout() 
        {
            doodleViewWidth = doodleView.getWidth(); 
            doodleViewHeight = doodleView.getHeight();
        }
  });

all I have done is just added ViewTreeObserver class name before OnGlobalLayoutListener().



来源:https://stackoverflow.com/questions/15053630/android-get-dimension-of-extended-view-using-addongloballayoutlistener-but-fail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!