首先自定义控件有什么用呢?当有一种组合控件在很多活动的布局中都要使用到的时候,如果没有自定义控件,那么在每个活动的布局都要写一次重复的代码,这样子就会使代码累赘。
这时就要使用到自定义控件了,自定义控件的步骤如下:
第一步
完成自定义控件的布局文件(.xml文件)
如下面的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:orientation="horizontal" >
<Button
android:id="@+id/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="退出" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textSize="20sp"
android:layout_weight="1"
android:text="标题内容" />
<Button
android:id="@+id/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="next" />
</LinearLayout>
第二步
定义一个类继承于ViewGroup下的任意子类,一般为LinearLayout(必须重写LinearLayout中的带两个参数的构造方法,在布局中引入这个TitleLayout控件就会调用这个构造函数。LayoutInflater的inflater方法中接收两个参数,一个是要加载的布局文件的id,一个是给加载好的布局添加一个父布局,这里是我们要指定为TitleLayout,于是直接传入this)
package com.jsako.ui;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.jsako.R;
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
View view=LayoutInflater.from(context).inflate(R.layout.title,this);
init(view);
}
private void init(View view) {
Button btn_back=(Button) findViewById(R.id.btn_back);
Button btn_next=(Button) findViewById(R.id.btn_next);
btn_back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity)getContext()).finish();
}
});
btn_next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(),"你点击了next", 0).show();
}
});
}
}
第三步
使用这个自定义控件(添加自定义控件和添加普通控件的方式基本一样,只不过在添加自定义控件的时候我们需要指明控件的完整类名,包名在这里是不可以省略的)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}" > <com.jsako.ui.TitleLayout android:layout_width="match_parent" android:layout_height="wrap_content" > </com.jsako.ui.TitleLayout> </RelativeLayout>
原文:http://www.cnblogs.com/Jsako/p/5647900.html