The value of 'bottomHeight' is 0 because 'getBottom()' returns the bottom position of the view relative to its parent view. If the view has not been laid out yet, it will return 0. Make sure that the view has been measured and laid out before calling 'getBottom()'.

You can ensure the view has been laid out in a few ways:

  1. Call getBottom() after onWindowFocusChanged(): This method is called when the window containing your view gains or loses focus. After the window has focus, you can be sure the view has been laid out.
  2. Use a ViewTreeObserver: The ViewTreeObserver can listen for events related to the view tree, including when the view has been laid out. You can add an observer and call 'getBottom()' in the onPreDraw() callback.
  3. Use a Handler with a delay: You can delay the call to 'getBottom()' using a Handler. This gives the system time to measure and lay out the view before you attempt to retrieve its bottom position.

Example:

ImageView imageView = findViewById(R.id.imageView);

// Using a Handler
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        int bottomHeight = imageView.getBottom();
        // Now bottomHeight should contain the correct value
    }
}, 100); // Delay for 100 milliseconds

By using one of these methods, you can ensure that 'getBottom()' returns the correct value and avoid the issue of getting 0.

Android ImageView getBottom() Returns 0: Why and How to Fix

原文地址: https://www.cveoy.top/t/topic/b99j 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录