android——获取view的宽高-创新互联-古蔺大橙子建站
RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
android——获取view的宽高-创新互联
  1. 在activity生命周期方法:onCreate(),onStart(),onResume()中调用View.getWidth()和View.getHeight()方法获取View的高度是不可行的,因为此时布局没有加载是不可见状态。

    创新互联公司是一家专注于网站设计制作、网站制作与策划设计,定陶网站建设哪家好?创新互联公司做网站,专注于网站建设10多年,网设计领域的专业建站公司;建站业务涵盖:定陶等地区。定陶做网站价格咨询:18980820575

    还有当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 width3 = textView.getMeasuredWidth();
		System.out.println("first: 宽: " + width3 + "  高: " + 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);
			}

		});
	}

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网站标题:android——获取view的宽高-创新互联
标题来源:http://scgulin.cn/article/jjphj.html