先推荐几个比较好的博客:http://my.csdn.net/sinyu890807
http://my.csdn.net/dj0379
http://blog.csdn.net/congqingbin/article/details/7869730
这周要去北戴河旅游,估计要等到下周才能把博客写完,我这周看的是自定义view这块,因为几乎所以面试都问道自定义view这块,而这块正好是我的弱项,所以我趁现在好好看看这块。
今天写的是自绘控件的学习心得,案例会放到这个系列的最后一个博客中
自定义view :就是自己编写控件,不用系统提供的标准控件。
自定义view分为:(1)自绘控件:继承view,在onDraw()中自己绘制
(2)组合控件:将系统的控件组合到一起
(3)继承控件:继承现有的控件,然后加入一下新的功能
1.继承控件
继承已有的控件,重写构造函数
简单的案例,继承TextView,重写它的属性
(1)在values下新建一个attrs.xml,用来定义一系列属性,比如字体颜色,字体大小等等
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomTextView">
<attr name="value" format="string"/>
<attr name="textSize" format="float"/>
</declare-styleable>
</resources>
注:
<declare-styleable></declare-styleable>是给自定义控件添加属性用的,里面的 name="CustomTextView"表示该属性集的名字
<attr></attr>表示属性。里面的format表示类型(string , integer , dimension , reference , color , enum......)
这个属性集合主要是在(2)中获取其属性。格式是CustomTextView_value
(2)新建一个类,继承TextView,在有两个参数的构造方法中获取属性
TypedArray tyArray=context.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
this.value=tyArray.getString(R.styleable.CustomTextView_value);
this.textSize=tyArray.getFloat(R.styleable.CustomTextView_textSize, 25);
tyArray.recycle();
this.setText(value);
this.setTextSize(textSize);
this.setTextColor(Color.RED);
(3)在xml中调用写好的类,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res/com.yang.customviewsemo"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.yang.customviewsemo.customview.CustomTextView
android:id="@+id/custonRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:value="@string/radiobutton_value"
android:textColor="#000000"/>
</LinearLayout>
注:在开头引用xmlns:custom="http://schemas.android.com/apk/res/com.yang.customviewsemo",res后 面的是项目的包名,然后就可以在布局界面中引用你定义的属 性custom:value="@string/radiobutton_value"