1.问题所在
.getLeft() .getRight() .getTop() .getBottom(),是获取当前view相对于父view的相应距离,但是获取的时机错误的话,view的四个值就获取不到。先来看个例子
我一共在六个地方获取了view的getLeft和getRight
1)在onCreate中获取
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_testanim); initPop(); mHandlerPlus = new HandlerPlus(this); mImg = (ImageView) findViewById(R.id.mImg_pop); Log.e(TAG, "onCreate: &&&&&&&&&&&&&&"); Log.e(TAG, "mImg.getLeft()--->"+mImg.getLeft()); Log.e(TAG, "mImg.getRight()--->"+mImg.getRight()); }
2)在onAttachToWindow中获取
@Override public void onAttachedToWindow() { super.onAttachedToWindow(); Log.e(TAG, "onAttachedToWindow: *************************"); Log.e(TAG, "mImg.getLeft()--->"+mImg.getLeft()); Log.e(TAG, "mImg.getRight()--->"+mImg.getRight()); }3)在布局监听中获取
View.OnAttachStateChangeListener mOnAttachStateChangeListener = new View.OnAttachStateChangeListener() { @Override public void onViewAttachedToWindow(View v) { parentHeight = getWindowWH(1); parentWidth = getWindowWH(0); viewHeight = dealViewWH(img_one, 1); viewWidth = dealViewWH(img_one, 0); Log.e(TAG, "onViewAttachedToWindow: ====================="); Log.e(TAG, "mImg.getLeft()--->"+mImg.getLeft()); Log.e(TAG, "mImg.getRight()--->"+mImg.getRight()); } @Override public void onViewDetachedFromWindow(View v) { } };4)在视图树的监听中获取
mImg.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Log.e(TAG, "onGlobalLayout:++++++++++++++++++++ "); Log.e(TAG, "mImg.getLeft()--->"+mImg.getLeft()); Log.e(TAG, "mImg.getRight()--->"+mImg.getRight()); } });5)在view的post中异步获取
mImg.post(new Runnable() { @Override public void run() { Log.e(TAG, "run: $$$$$$$$$$$$$$$$"); Log.e(TAG, "mImg.getLeft()--->"+mImg.getLeft()); Log.e(TAG, "mImg.getRight()--->"+mImg.getRight()); } });6)在window焦点改变的时候获取
@Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus){ Log.e(TAG, "onWindowFocusChanged: %%%%%%%%%%%%%%%%%"); Log.e(TAG, "mImg.getLeft()--->"+mImg.getLeft()); Log.e(TAG, "mImg.getRight()--->"+mImg.getRight()); } }只有后三种的获取时机下才真确的拿到了值。
2.原因所在
一个view要在界面上显示,要经过Measure,Layout,Draw三个步骤,view的位置确定是在Measure和Layout之后才被赋予的,所以要在view完成上述两个步骤之后才能正确获取到相应的数值
在(4)视图树中可以拿到值,但是这个方法会调用两次,会对你以后的操作产生影响