android:使用addOnGlobalLayoutListener获取扩展视图的尺寸,但失败 [英] android: get dimension of extended view using addOnGlobalLayoutListener but fails

查看:817
本文介绍了android:使用addOnGlobalLayoutListener获取扩展视图的尺寸,但失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现以下addOnGlobalLayoutListener,以便在主要活动(A)的OnCreate部分中测量扩展视图(doodleView).

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();
        }
  });

但是,对于addOnGlobalLayoutListener,它带有红色下划线并带有以下错误声明:

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!

推荐答案

我做了非常相似的事情,但是后来发现onMeasure.因此,如果这本质上是一次性的,请尝试执行与此类似的操作:

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

您可能忘记了.

这篇关于android:使用addOnGlobalLayoutListener获取扩展视图的尺寸,但失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆