建立网站赚钱 优帮云,pt网站怎么做,做网站一定要正版系统吗,网站建设时如何选择合适的服务器前几天#xff0c;在自定义控件的时候碰到个问题#xff0c;就是在如何获取自定义控件的高宽。在自定义控件类的构造函数中#xff0c;本来以为可以轻松获取#xff0c;但事实不是这样。我测试了下面代码#xff1a; 先是布局代码#xff1a; com.lml.getvalues.MyVi… 前几天在自定义控件的时候碰到个问题就是在如何获取自定义控件的高宽。在自定义控件类的构造函数中本来以为可以轻松获取但事实不是这样。我测试了下面代码 先是布局代码 com.lml.getvalues.MyView android:idid/myView android:layout_widthmatch_parent android:layout_height150px android:background#ff0000 / 再是MyView的构造函数的代码 public MyView(Context context, AttributeSet attrs) { super(context, attrs); a在MyView构造函数中 : MeasuredWidth:this.getMeasuredWidth();MeasuredHeight:this.getMeasuredHeight(); Width:this.getWidth();Height:this.getHeight()\n; String h,w; for(int i 0 ;i attrs.getAttributeCount();i){ if(layout_height.equals(attrs.getAttributeName(i))){ hattrs.getAttributeValue(i); }else if(layout_width.equals(attrs.getAttributeName(i))){ wattrs.getAttributeValue(i); } } b在构造函数attrs中 : width:w;height:h\n; } 编译得到a在MyView构造函数中 : MeasuredWidth:0;MeasuredHeight:0;Width:0;Height:0. b在构造函数attrs中 : width:-1;height:150.0px 结果显示当width为match_parent等数值时只显示-1等不能满足我的需求。 然后我试着在相应Activity的onCreate中获取高宽获得的全部是0.但我在onCreate中的加了个点击控件获取高宽事件能正确获取高宽。我在网上查了下资料因为在onCreate中控件还未被度量所以获取肯定为0.网上有获取三个方法方法如下 方法一不知道为何在我这实现不了咋onCreate中添加如下代码: int w View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int h View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); myView.measure(w, h); int height myView.getMeasuredHeight(); int width myView.getMeasuredWidth(); tvValues.append(方法一: height:height ,width: width\n); 方法二可以实现代码如下 ViewTreeObserver vto2 myView.getViewTreeObserver(); vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { Override public void onGlobalLayout() { myView.getViewTreeObserver().removeGlobalOnLayoutListener(this); tvValues.append( 方法二: height:myView.getHeight() ,width: myView.getWidth()\n); } }); 但我发现removeGlobalOnLayoutListener在API 级别 16 开始已经废弃如果去掉系统会读取多次。 再来看看方法三代码如下 ViewTreeObserver vto myView.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { myView.getViewTreeObserver().removeOnPreDrawListener(this); int height myView.getMeasuredHeight(); int width myView.getMeasuredWidth(); tvValues.append(方法三: height:height ,width: width ..\n); return true; } }); 我在网上资料的基础上添加了myView.getViewTreeObserver().removeOnPreDrawListener(this);这一条这个可以保证系统运行一次。 转载于:https://blog.51cto.com/tongfu1013/1680753