View的onDraw函数不被调用 .

 

参考:
http://blog.sina.com.cn/s/blog_4b50130d0100u0uk.html
http://blog.csdn.net/hearrt/article/details/7001358

解决自定义View的onDraw()方法不被执行问题。

当我们需要创建一个直接或间接继承View的类,以便重写onDraw()方法,实现自定义的View的绘制时,往往会发现onDraw方法并没有正确的执行。
你需要在你直接或者間接繼承View的類的構造函數中加入下面的語句:

      setWillNotDraw(false);

這個標記在View裡是不設定的。但是像View的一些子類如ViewGroup是可以設定的。典型的,你如果複寫了onDraw(Canvas)方法,你需要清除此標記。

 

 

1.要实现一个容器  如此做:

  1. public class CustomFrameLayout extends FrameLayout {  
  2.         private static final String TAG = "CustomFrameLayout";  
  3.           
  4.         public CustomFrameLayout(Context context) {  
  5.             super(context);  
  6.             this.setWillNotDraw(false);//必须  
  7.         }  
  8.           
  9.         public void onDraw(Canvas canvas){  
  10.             super.onDraw(canvas);  
  11.             drawSomething(canvas);  
  12.         }  
  13.     }  
public class CustomFrameLayout extends FrameLayout {
		private static final String TAG = "CustomFrameLayout";
		
		public CustomFrameLayout(Context context) {
			super(context);
			this.setWillNotDraw(false);//必须
		}
		
		public void onDraw(Canvas canvas){
			super.onDraw(canvas);
			drawSomething(canvas);
		}
	}

构造函数中没有 this.setWillNotDraw(false)这句话时候 onDraw函数始终不被调用 直到添加上之后才可以成功调用onDraw函数

仔细查看onDraw函数的说明:

public void setWillNotDraw (boolean willNotDraw)
Since:  API Level 1

If this view doesn't do any drawing on its own, set this flag to allow further optimizations. By default, this flag is not set on View, but could be set on some View subclasses such as ViewGroup. Typically, if you overrideonDraw(Canvas) you should clear this flag.

Parameters
willNotDraw whether or not this View draw on its own

总之,要想再自定义的画一些东西 就要进行setWillNotDraw(false).
2.如果你有两个容器 A 和 a,a是放在A之中。如果都对这两个容器设置了 setWillNotDraw(false),那么你将会看到一个“奇迹":a中被添加进来的控件都不透明了,这时候不要怀疑你的控件图片不是透明的,是因为你对A容器设置了setWillNotDraw(false),尝试将其去掉,问题就OK了


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值