【转】android 自定义控件

时间:2023-03-09 13:27:56
【转】android 自定义控件

Android自定义View实现很简单

继承View,重写构造函数、onDraw,(onMeasure)等函数。

如果自定义的View需要有自定义的属性,需要在values下建立attrs.xml。在其中定义你的属性。

在使用到自定义View的xml布局文件中需要加入xmlns:前缀="http://schemas.android.com/apk/res/你的自定义View所在的包路径".

在使用自定义属性的时候,使用前缀:属性名,如my:textColor="#FFFFFFF"。

实例:

  1. package  demo.view.my;
  2. import  android.content.Context;
  3. import  android.content.res.TypedArray;
  4. import  android.graphics.Canvas;
  5. import  android.graphics.Color;
  6. import  android.graphics.Paint;
  7. import  android.graphics.Paint.Style;
  8. import  android.util.AttributeSet;
  9. import  android.view.View;
  10. /**
  11. * 这个是自定义的TextView.
  12. * 至少需要重载构造方法和onDraw方法
  13. * 对于自定义的View如果没有自己独特的属性,可以直接在xml文件中使用就可以了
  14. * 如果含有自己独特的属性,那么就需要在构造函数中获取属性文件attrs.xml中自定义属性的名称
  15. * 并根据需要设定默认值,放在在xml文件中没有定义。
  16. * 如果使用自定义属性,那么在应用xml文件中需要加上新的schemas,
  17. * 比如这里是xmlns:my="http://schemas.android.com/apk/res/demo.view.my"
  18. * 其中xmlns后的“my”是自定义的属性的前缀,res后的是我们自定义View所在的包
  19. * @author Administrator
  20. *
  21. */
  22. public   class  MyView  extends  View {
  23. Paint mPaint; //画笔,包含了画几何图形、文本等的样式和颜色信息
  24. public  MyView(Context context) {
  25. super (context);
  26. }
  27. public  MyView(Context context, AttributeSet attrs){
  28. super (context, attrs);
  29. mPaint = new  Paint();
  30. //TypedArray是一个用来存放由context.obtainStyledAttributes获得的属性的数组
  31. //在使用完成后,一定要调用recycle方法
  32. //属性的名称是styleable中的名称+“_”+属性名称
  33. TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);
  34. int  textColor = array.getColor(R.styleable.MyView_textColor,  0XFF00FF00 );  //提供默认值,放置未指定
  35. float  textSize = array.getDimension(R.styleable.MyView_textSize,  36 );
  36. mPaint.setColor(textColor);
  37. mPaint.setTextSize(textSize);
  38. array.recycle(); //一定要调用,否则这次的设定会对下次的使用造成影响
  39. }
  40. public   void  onDraw(Canvas canvas){
  41. super .onDraw(canvas);
  42. //Canvas中含有很多画图的接口,利用这些接口,我们可以画出我们想要的图形
  43. //mPaint = new Paint();
  44. //mPaint.setColor(Color.RED);
  45. mPaint.setStyle(Style.FILL); //设置填充
  46. canvas.drawRect(10 ,  10 ,  100 ,  100 , mPaint);  //绘制矩形
  47. mPaint.setColor(Color.BLUE);
  48. canvas.drawText("我是被画出来的" ,  10 ,  120 , mPaint);
  49. }
  50. }

相应的属性文件:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <declare-styleable name="MyView">
  4. <attr name="textColor" format="color"/>
  5. <attr name="textSize" format="dimension"/>
  6. </declare-styleable>
  7. </resources>

在布局文件中的使用: