从addOnPreDrawListener()获取值

时间:2016-12-19 21:08:38

标签: android android-viewtreeobserver

我还没有理解如何从下面的方法返回值,我试图返回int,但它向我显示了一个无法解决的奇怪错误。这是代码:

private void showTheEnemy() {

    ViewTreeObserver vto = radarImage.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw() {
            radarImage.getViewTreeObserver().removeOnPreDrawListener(this);
            yradar_height = radarImage.getMeasuredHeight();
            xradar_width = radarImage.getMeasuredWidth();
            return true;
        }
    });
    coordinateText.setText(yradar_height + " " + xradar_width);
}

我理解方法中没有更新值,因为当我使用setText()方法时,int值为0。

2 个答案:

答案 0 :(得分:0)

由于在设置文本之前未触发内部方法,因此得到零。这些值设置为您上次初始化它们时的任何值。

设置回调中的文本。

private TextView coordinateText;
private int xradar_width = 0;
private int yradar_height = 0;

private void showTheEnemy() {

    ViewTreeObserver vto = radarImage.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw() {

            yradar_height = radarImage.getMeasuredHeight();
            xradar_width = radarImage.getMeasuredWidth();

            coordinateText.setText(String.format("%d %d", 
                yradar_height,
                xradar_width 
            ));

            radarImage.getViewTreeObserver().removeOnPreDrawListener(this);
            return true;
        }
    });

    // Your values are still 0 here

}

或传递给另一种方法。

private TextView coordinateText;

private void showTheEnemy() {

    ViewTreeObserver vto = radarImage.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw() {

         setCoordinate(coordinateText,  
                radarImage.getMeasuredHeight(),
                radarImage.getMeasuredWidth() ));
            radarImage.getViewTreeObserver().removeOnPreDrawListener(this);
            return true;
        }
    });

}

private static void setCoordinate(TextView tv, int xPos, int yPos) {
     tv.setText(String.format("%d %d", xPos, yPos));
}

答案 1 :(得分:0)

获得radarImage宽度和高度时设置值:

private void showTheEnemy() {
    ViewTreeObserver vto = radarImage.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw() {
            radarImage.getViewTreeObserver().removeOnPreDrawListener(this);
            yradar_height = radarImage.getMeasuredHeight();
            xradar_width = radarImage.getMeasuredWidth();
            coordinateText.setText(yradar_height + " " + xradar_width);
            return true;
        }
    });
    coordinateText.setText(yradar_height + " " + xradar_width);
}

编辑: 创建类字段,并在提供新值时传递您需要它们的值。