Android(安卓)获取View高度的4种方法
16lz
2021-01-24
1 通过 looper 队列
/** * 通过 looper 队列 */ private void getHeight1() { tvText.post(new Runnable() { @Override public void run() { int height = tvText.getHeight(); Log.i(TAG, "MainActivity;getHeight1;height=" + height); } }); }
2 当视图树的布局发生改变时
/** * 当视图树的布局发生改变时 */ private void getHeight2() { tvText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { tvText.getViewTreeObserver().removeOnGlobalLayoutListener(this); int height = tvText.getHeight(); Log.i(TAG, "MainActivity;getHeight2;height=" + height); } }); }
3 当视图树的进行绘制时
/** * 当视图树的进行绘制时 */ private void getHeight3() { tvText.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { tvText.getViewTreeObserver().removeOnPreDrawListener(this); int height = tvText.getHeight(); Log.i(TAG, "MainActivity;getHeight3;height=" + height); return false; } }); }
4 view 布局改变时
/** * view 布局改变时 */ private void getHeight4() { tvText.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { tvText.removeOnLayoutChangeListener(this); int height = tvText.getHeight(); Log.i(TAG, "MainActivity;getHeight4;height=" + height); } }); }
更多相关文章
- 大话企业级Android应用开发实战 用户界面
- Android(安卓)GridView设置条目的高度与宽度相等、GridView条目
- Android(安卓)DataBinding ViewPage + Fragment 封装
- Android(安卓)dialog 对话框自定义布局
- Android学习笔记:TabHost 和 FragmentTabHost
- Android程序中输入法弹出的时候如何不遮挡输入,与布局相配
- 2019年最新Android常用开源库汇总上篇(持续更新)