首页 > 系统 > Android > 正文

android获取view宽高的时机

2019-11-08 00:21:09
字体:
来源:转载
供稿:网友

关键点:获取宽高应该在view的onLayout之后,这个时候,view已经确定算出宽高。 error:

/** * 在onCreate,onResume方法中调用,用于获取TextView的宽度和高度都是0 */PRivate void getTextHeightAndWidth() { // 我们定义的用于获取宽度和高度的组件 titleText = (TextView) findViewById(R.id.text_title); int height = titleText.getHeight(); int width = titleText.getWidth(); Log.i(TAG, "height:" + height + " " + "width:" + width); }06-26 20:12:15.356 19453-19453/uuch.com.Android_viewheight I/MainActivity: height:0 width:0

正确时机: 1.在监听事件中获取:

/** * 这里的button1是我们定义的Button组件,并且我们重写了Button的点击事件,在其中调用了获取组件宽高的方法 */button1 = (Button) findViewById(R.id.button1);button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getTextHeightAndWidth(); } });

2.重写Activity的onWindowFocusChanged方法

/** * 重写Acitivty的onWindowFocusChanged方法 */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); /** * 当hasFocus为true的时候,说明Activity的Window对象已经获取焦点,进而Activity界面已经加载绘制完成 */ if (hasFocus) { int widht = titleText.getWidth(); int height = titleText.getHeight(); Log.i(TAG, "onWindowFocusChanged width:" + widht + " " + " height:" + height; } }

3.为组件添加OnGlobalLayoutListener事件监听

/** * 为Activity的布局文件添加OnGlobalLayoutListener事件监听,当回调到onGlobalLayout方法的时候我们通过getMeasureHeight和getMeasuredWidth方法可以获取到组件的宽和高 */private void initOnLayoutListener() { final ViewTreeObserver viewTreeObserver = this.getWindow().getDecorView().getViewTreeObserver(); viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Log.i(TAG, "开始执行onGlobalLayout()........."); int height = titleText.getMeasuredHeight(); int width = titleText.getMeasuredWidth(); Log.i(TAG, "height:" + height + " width:" + width); // 移除GlobalLayoutListener监听 MainActivity.this.getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); }

4.使用View.post方法获取组件的宽高

/** * 使用View的post方法获取组件的宽度和高度,这里用的是异步消息获取组件的宽高,而这里的异步消息的执行过程是在主进程的主线程的Activity绘制流程之后,所以这时候可以获取组件的宽高。 */private void initViewHandler() { titleText.post(new Runnable() { @Override public void run() { int width = titleText.getWidth(); int height = titleText.getHeight(); Log.i(TAG, "initViewHandler height:" + height + " width:" + width); } }); }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表