Determining the size of an Android view at runtime

前端 未结 12 2009
陌清茗
陌清茗 2020-11-22 09:59

I am trying to apply an animation to a view in my Android app after my activity is created. To do this, I need to determine the current size of the view, and then set up an

12条回答
  •  情书的邮戳
    2020-11-22 10:24

    You can get both Position and Dimension of the view on screen

     val viewTreeObserver: ViewTreeObserver = videoView.viewTreeObserver;
    
    if (viewTreeObserver.isAlive) {
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                //Remove Listener
                videoView.viewTreeObserver.removeOnGlobalLayoutListener(this);
    
                //View Dimentions
                viewWidth = videoView.width;
                viewHeight = videoView.height;
    
                //View Location
                val point = IntArray(2)
                videoView.post {
                    videoView.getLocationOnScreen(point) // or getLocationInWindow(point)
                    viewPositionX = point[0]
                    viewPositionY = point[1]
                }
    
            }
        });
    }
    

提交回复
热议问题