做过了一段时间的安卓开发都会接触到自定义控件,那么对于自定义控件大家都有什么样的看法呢?自定义控件他的优势是明显的,设计他的思想又有哪些呢?会用到什么模式呢?希望大家看了这个文章之后,可以发表自己对于自定义控件的看法和思想,这个帖就是为了跟大家交流而发。下面是我自己的一些看法,大侠们请指导!!! j*XhBWE?
?^f=7e8]
自定义View: r0xmDJ@y
在这里我们先来了解自定义控件view所需要的一些基础知识,以及常见做法。 LN!e_b
自定义View类的构造方法 IXA3G7$)
创建自定义控件的3种主要实现方式: cUB+fH<B2
>5%;NI5
G
1)继承已有的控件来实现自定义控件 PjxZ3O
主要是当要实现的控件和已有的控件在很多方面比较类似, 通过对已有控件的扩展来满足要求。 4ju=5D];
=eHoJq
2)通过继承一个布局文件实现自定义控件 \x(ILk|'c
一般来说做组合控件时可以通过这个方式来实现。 [p:mja.6y
注意此时不用onDraw方法,在构造函数中通过inflater加载自定义控件的布局文件,再addView(view),自定义控件的图形界面就加载进来了。 |L }1@0i
例如: r9\7I7z
假设我已经有了一个布局的XML文件,里面有一个textview和一个imageview,那么在自定义view的构造方法里这样写就可以使用刚刚的布局XML啦。 q$ZmR]p
[mw_shl_code=java,true]public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.myView, this);
imageView=(ImageView) findViewById(R.id.imageView1);
textView=(TextView)findViewById(R.id.textView1);
}[/mw_shl_code] vGST{Lz;
#uc9eh}CWO
3)通过继承view类来实现自定义控件,使用GDI绘制出组件界面,一般无法通过上述两种方式来实现时用该方式。 p#QR^|7"
自定义View增加属性的两种方法 ^F="'/Pq[
gt>k]0
1)在View类中定义。通过构造函数中引入的AttributeSet 去查找XML布局的属性名称,然后找到它对应引用的资源ID去找值。 ?D?ldg
Fk4T>8q2;
在下面自定义了两个属性Text, Src。 }M0GPpv
布局文件: 9-`P\/
[mw_shl_code=xml,true]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.apkbus.MyView
android:id="@+id/myView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Text="@string/hello_world"
Src="@drawable/logo"/>
</LinearLayout>[/mw_shl_code] f6$$e+
C)z?-f
属性Text, Src在自定义View类的构造方法中读取。 y'
r I1eF
Java代码: jl)7Jd
[mw_shl_code=java,true]public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
int resourceId = 0;
int textId = attrs.getAttributeResourceValue(null, "Text",0);
int srcId = attrs.getAttributeResourceValue(null, "Src", 0);
mtext = context.getResources().getText(textId).toString();
}[/mw_shl_code] ]iq2_{q
m|by^40A(
R5b!Ao
2)通过XML为View注册属性。与Android提供的标准属性写法一样。 Xus TU
例如: eE0'3?q(
需要自定义属性Text,Select和Src,先创建attrs.xml进行属性声明, 文件放在values目录下。 EvJ<X,Bo
[mw_shl_code=xml,true]<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="Text" format="reference|string"></attr>
<attr name="Select" >
<enum name="open" value="1"></enum>
<enum name="close" value="0"></enum>
</attr>
<attr name="Src" format="reference|integer"></attr>
</declare-styleable>
</resources>[/mw_shl_code] <