Determining the size of an Android view at runtime

前端 未结 12 1739
陌清茗
陌清茗 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:13

    Here is the code for getting the layout via overriding a view if API < 11 (API 11 includes the View.OnLayoutChangedListener feature):

    public class CustomListView extends ListView
    {
        private OnLayoutChangedListener layoutChangedListener;
    
        public CustomListView(Context context)
        {
            super(context);
        }
    
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b)
        {
            if (layoutChangedListener != null)
            {
                layoutChangedListener.onLayout(changed, l, t, r, b);
            }
            super.onLayout(changed, l, t, r, b);
        }
    
        public void setLayoutChangedListener(
            OnLayoutChangedListener layoutChangedListener)
        {
            this.layoutChangedListener = layoutChangedListener;
        }
    }
    public interface OnLayoutChangedListener
    {
        void onLayout(boolean changed, int l, int t, int r, int b);
    }
    
    0 讨论(0)
  • 2020-11-22 10:13

    In Kotlin file, change accordingly

     Handler().postDelayed({
    
               Your Code
    
            }, 1)
    
    0 讨论(0)
  • 2020-11-22 10:15

    Use below code, it is give the size of view.

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
           super.onWindowFocusChanged(hasFocus);
           Log.e("WIDTH",""+view.getWidth());
           Log.e("HEIGHT",""+view.getHeight());
    }
    
    0 讨论(0)
  • 2020-11-22 10:18

    You can check this question. You can use the View's post() method.

    0 讨论(0)
  • 2020-11-22 10:18

    I was also lost around getMeasuredWidth() and getMeasuredHeight() getHeight() and getWidth() for a long time.......... later i found that getting the view's width and height in onSizeChanged() is the best way to do this........ you can dynamically get your CURRENT width and CURRENT height of your view by overriding the onSizeChanged() method.

    might wanna take a look at this which has an elaborate code snippet. New Blog Post: how to get width and height dimensions of a customView (extends View) in Android http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html

    0 讨论(0)
  • 2020-11-22 10:19

    This works for me in my onClickListener:

    yourView.postDelayed(new Runnable() {               
        @Override
        public void run() {         
            yourView.invalidate();
            System.out.println("Height yourView: " + yourView.getHeight());
            System.out.println("Width yourView: " + yourView.getWidth());               
        }
    }, 1);
    
    0 讨论(0)
提交回复
热议问题