有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android在视图完成后执行

我是新来的,所以对我放松点。 我正在尝试执行一段代码,需要知道设备旋转后ImageView的新宽度和高度

下面的代码捕获了配置更改,但是ImageView实际上还没有更改,所以我无法获得准确的高度和宽度

// This fires whenever the configuration of the device changes (Portrait to Landscape of vice versa)
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }

// This procedure moves the items based on the new size of the ImageView.
   this.ShowMeasurements();
}

我已经寻找并研究了一些应该有效的方法,但我的答案很短

如有任何建议,将不胜感激


共 (1) 个答案

  1. # 1 楼答案

    可以肯定的是,该视图具有精确的大小。您可以在onCreate()中尝试以下代码:

    imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int viewWidth = imageView.getWidth();
                int viewHeight = imageView.getHeight();
                if (viewWidth > 0 && viewHeight > 0) {
                    //do some stuff here
                }
                //we remove this listener to not being notified every time the view
                //changes it's size. 
                //But if you need this info every time, just remove the last line
                imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
    

    其中,imageView是对您的ImageView的引用