Android自定义控件知识点杂记

235 阅读1分钟

自定义控件遇到的一些杂七杂八的知识点记录一下,避免忘记.

  • ondraw和dispatchDraw和区别: onDraw()的意思是绘制视图本身, dispatchDraw()的意思是绘制子视图. 无论view还是viewgroup对它们俩的调用顺序都是ondraw()->dispatchDraw(); 在viewgroup中,当他有背景的时候会调用onDraw()方法,否则会跳过onDraw()直接调用dispatchDraw(); 所以一般绘制viewgroup的时候一般都重写diapatchDraw();绘制view的时候一般都重写ondraw();

  • dispatchDraw()中的super.dispatchDraw(canvas): super.dispatchDraw(canvas)的作用是绘制出该控件的所有子控件, 所以如果把super.dispatchDraw(canvas)放在前面的就会先绘制自己,再绘制子控件,同理,如果把super.dispatchDraw(canvas)放在后面的,就会先绘制子控件在绘制自己;

  • 如何判断手指是否点击到某个控件内部: android 提供了getLocationOnScreen(int[] location)函数,该函数的功能是获取当当前控件所在的屏幕的位置,需要传进去一个数组,在执行后会把left,top 赋值给location[0],location[1]; 代码如下:

 Rect rect = new Rect();
 int[] location = new int[2];
 mTextView.getLocationOnScreen(location); 
rect.left = location[0]; rect.top = location[1]; 
rect.right = mTextView.getWidth() + location[0]; 
rect.bottom = mTextView.getHeight() + location[1];
if (rect.contains((int) event.getRawX(), (int) event.getRawY()))
 { 
        mTouch = true;
}

持续更新....