首页 > 移动平台 > 详细

android——获取view的宽高

时间:2015-01-21 20:30:25      阅读:413      评论:0      收藏:0      [点我收藏+]
  1. 在activity生命周期方法:onCreate(),onStart(),onResume()中调用View.getWidth()和View.getHeight()方法获取View的高度是不可行的,因为此时布局没有加载是不可见状态。

    还有当view的可见状态为:GONE,时获取的宽高也是0;

2. 解决办法:

(1)直接测量:

private void first() {
		int width = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		int height = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		textView.measure(width, height);
		int height1 = textView.getMeasuredHeight();
		int width2 = textView.getMeasuredWidth();
		System.out.println("first: 宽: " + width2 + "  高: " + height1);
	}

(2)添加绘制view之前的监听

private void second() {
		ViewTreeObserver vto = textView.getViewTreeObserver();

		vto.addOnPreDrawListener(new

		ViewTreeObserver.OnPreDrawListener() {

			public boolean onPreDraw() {

				int height = textView.getMeasuredHeight();

				int width = textView.getMeasuredWidth();

				System.out.println("second:  宽:" + width + "  高: " + height);

				return true;
			}

		});
	}

(3)添加整体布局监听

private void third() {
		ViewTreeObserver vto = textView.getViewTreeObserver();

		vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

			public void onGlobalLayout() {

				textView.getViewTreeObserver().removeGlobalOnLayoutListener(
						this);

				int height = textView.getMeasuredHeight();

				int width = textView.getMeasuredWidth();
				System.out.println("third:  宽:" + width + "  高: " + height);
			}

		});
	}


本文出自 “Androidcamera小结” 博客,请务必保留此出处http://7183397.blog.51cto.com/7173397/1606535

android——获取view的宽高

原文:http://7183397.blog.51cto.com/7173397/1606535

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!