自定义组合控件:
以三国杀游戏武将为例,包括武将头像,血条,装备区
1.先定义该组合的XML文件布局

1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="wrap_content"
4 android:layout_height="wrap_content"
5 android:orientation="horizontal" >
6 <LinearLayout
7 android:layout_width="wrap_content"
8 android:layout_height="wrap_content"
9 android:orientation="vertical"
10 >
11 <ImageView
12 android:id="@+id/touxiang"
13 android:layout_width="80dp"
14 android:layout_height="80dp"
15 android:maxWidth="80dp"
16 android:maxHeight="80dp"
17 >
18 </ImageView>
19 <ImageView
20 android:id="@+id/blood"
21 android:layout_width="wrap_content"
22 android:layout_height="wrap_content"
23 android:maxWidth="80dp"
24 android:maxHeight="20dp"
25 >
26 </ImageView>
27
28 </LinearLayout>
29
30 <LinearLayout
31 android:layout_width="wrap_content"
32 android:layout_height="wrap_content"
33 android:orientation="vertical"
34 android:layout_gravity="center_vertical"
35 >
36 <TextView
37 android:layout_width="wrap_content"
38 android:layout_height="wrap_content"
39 android:text="武器"
40 ></TextView>
41 <TextView
42 android:layout_width="wrap_content"
43 android:layout_height="wrap_content"
44 android:text="防具"
45 ></TextView>
46 <TextView
47 android:layout_width="wrap_content"
48 android:layout_height="wrap_content"
49 android:text="+1马"
50 ></TextView>
51 <TextView
52 android:layout_width="wrap_content"
53 android:layout_height="wrap_content"
54 android:text="-1马"
55 ></TextView>
56 </LinearLayout>
57
58 </LinearLayout>

2.自定义一个继承布局的类
public class GeneralFrame extends LinearLayout {
ImageView general;
ImageView blood;
TextView wuqi;
TextView fangju;
TextView jiayima;
TextView jianyima;
public GeneralFrame(Context context) {
//super(context);
// TODO Auto-generated constructor stub
this(context,null);
}
public GeneralFrame(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
//在构造函数中将Xml中定义的布局解析出来。
LayoutInflater.from(context).inflate(R.layout.generalframe, this, true);
general=(ImageView)findViewById(R.id.touxiang);
blood=(ImageView)findViewById(R.id.blood);
blood.setImageResource(R.drawable.blood);
//wuqi=(TextView)findViewById(R.id
}
可在XML文件里调用该类
< com.layouts.uitest.GeneralFrame
android:layout_height="wrap_content"
android:layout_width="wrap_content"
/>
也可以在代码中动态添加该类
GeneralFrame general=new GeneralFrame(this);
general.setGeneralImage(R.drawable.diaochan);
linear2.addView(general);
自定义View.
自定义类继承View
public class MyView extends View
{
public MyView (Context c,AttributeSet set)
{
}
@Override
public void onDraw(Canvas canvas)
{
}
}
调用方法同自定义控件一样。
自定义View的构造方法一定要选中 public MyView (Context c,AttributeSet set),系统会回调该构造方法