Android自定义View的一些理解

来源:互联网 发布:投资数据库终端 编辑:程序博客网 时间:2024/06/05 14:06

在我们写布局文件时,像button,ImageView,都是一个个view。那自定义view就可以理解为,”newbutton“或者"newiamgeView"。

那么在button类似的组件中,我们通过设置width,hight就可以改变他们的大小,这些属性当然是前辈们完成好,供我们使用的。

那现在我们想给我们自定义的view,添加一个属性,比如一个文本字体大小,或者文本的字体颜色,那要怎么做呢。可能你会想,咦为什么不直接写android:textSize=""这样去设置呢,那如果你这个View并没有像button有text这个属性,你又怎么设置呢。

好比你这个view中,定义了一个paint,想用paint画一个蓝色的园,那你还想android:textColor=“”去设置吗?明显是不行的嘛。

那又有同学想了,那简单啊就在onDraw直接定义就好了。

protected void onDraw(Canvas canvas){paint.setColor(Color.BLUE);}
但,你们想想看一个属性如果写死的话,那这个view就不好用了,比如你想设置button的width,然而它是写死的,你还会用它吗,是一个道理。

那要怎么实现属性的自定义呢。首先你需要

  1. 在res/values文件下定义一个attrs.xml文件.代码如下:  
  2. <?xml version="1.0" encoding="utf-8"?> 
  3. <resources> 
  4.     <declare-styleable name="MyView"> 
  5.         <attr name="textColor" format="color" /> 
  6.         <attr name="textSize" format="dimension" /> 
  7.     </declare-styleable> 
  8. </resources>   

然后在myView的构造函数中去获得

  1. public MyView(Context context,AttributeSet attrs)     
  2.     {     
  3.         super(context,attrs);     
  4.         mPaint = new Paint();     
  5.         //     
  6.         TypedArray a = context.obtainStyledAttributes(attrs,     
  7.                 R.styleable.MyView);     
  8.              
  9.         int textColor = a.getColor(R.styleable.MyView_textColor,     
  10.                 0XFFFFFFFF);     
  11.         float textSize = a.getDimension(R.styleable.MyView_textSize, 36);     
  12.              
  13.         mPaint.setTextSize(textSize);     
  14.         mPaint.setColor(textColor);     
  15.              
  16.         a.recycle();     
  17.     }


可能有同学奇怪你这步不也是写死了的吗,其实最后这个参数是默认值,就是不去设置时取这个值

  1.  int textColor = a.getColor(R.styleable.MyView_textColor,     
  2.                 0XFFFFFFFF);

然后在xml文件的使用。

<?xml    version="1.0" encoding="utf-8"?>   <LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"                   xmlns:test="http://schemas.android.com/apk/res/com.android.tutor"      android:orientation="vertical"      android:layout_width="fill_parent"      android:layout_height="fill_parent"      >   <TextView         android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello"      />   <com.android.tutor.MyView       android:layout_width="fill_parent"        android:layout_height="fill_parent"        test:textSize="20px"      test:textColor="#fff"  />   </LinearLayout>  

上述的代码来自http://weizhulin.blog.51cto.com/1556324/311453


0 0
原创粉丝点击