控件的继承关系
在此之前先看下关于View的继承关系,其中红色为常用控件。
自定义布局
自定义控件之前先定义控件的布局----这里做一个导航栏
两个Button和一个TextView
Title.xml
<?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="wrap_content"
android:background="#ff0000">
<Button
android:layout_margin="5dp"
android:textSize="24sp"
android:text="后退"
android:background="#000000"
android:layout_gravity="center"
android:textColor="#fff"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_gravity="center"
android:textSize="24sp"
android:text="标题"
android:gravity="center"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:layout_margin="5dp"
android:textSize="24sp"
android:text="前进"
android:background="#000000"
android:layout_gravity="center"
android:textColor="#fff"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
在使用的部分引入
<include layout="@layout/title" />
创建自定义控件
真正的自定义控件不只有布局,还有事件响应。所以还要为这个控件添加事件。
新建TitleLayout类继承LinearLayout,并重载时加入布局文件
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs){
super(context,attrs);
LayoutInflater.from(context).inflate(R.layout.title,this);
}
}
如何引入:这里的引入不再是用include,而是引入包名加类名的方式
<com.example.administrator.uicustomviews.TitleLayout
android:layout_height="wrap_content"
android:layout_width="match_parent" >
</com.example.administrator.uicustomviews.TitleLayout>
接下来为两个Button注册点击事件
public TitleLayout(Context context, AttributeSet attrs){
super(context,attrs);
LayoutInflater.from(context).inflate(R.layout.title,this);
Button left=(Button) findViewById(R.id.left);
Button right=(Button) findViewById(R.id.right);
left.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity) getContext()).finish();
}
});
right.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(),"right",Toast.LENGTH_LONG).show();
}
});
}
测试