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