---
title: "【Android】创建自定义复合控件"
author: "dyingbleed"
date: "2011-10-04T16:21:02Z"
tags: []
categories: ["移动开发"]
slug: "android"
draft: false
lastmod: "2011-10-04T16:21:02Z"
id: 1185223
url: "https://dyingbleed.iteye.com/blog/1185223"
---

复合控件是将一组相互关联的已有控件整合，从而可以当作单个控件使用。

 

创建复合控件的步骤：

 

1. 创建一个扩展布局的类
2. 实现构造方法，并在构造方法中，首先实现超类的构造方法super(...)
3. 复合组件可以像其他视图一样在XML中声明创建，组件名为该类的完整名称（包名+类名），并在构造方法中实现超类构造方法super(Context contex, AttributeSet attrs)。
4. 通过attrs获取自定义属性值，对子控件进行初始化设置。
5. 根据需要扩展该复合组件方法

示例代码：

图标控件（包含图标和标题）

```
package lizhen.appstore.ext;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 图标（图标+标题）
 * */
public class Icon extends LinearLayout {
	
	private ImageButton icon; //图标
	private TextView title; //标题
	
	public Icon(Context context, AttributeSet attrs) {
		super(context, attrs);
		
		setOrientation(VERTICAL); //设置方向竖直
		/*
		 * 图标初始化
		 * */
		icon = new ImageButton(context);
		int srcID = attrs.getAttributeResourceValue(null, "src", 0);
		if(srcID == 0) {
			//TODO
		} else {
			icon.setImageResource(srcID);
		}
		LayoutParams layoutParames = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		icon.setPadding(5, 5, 5, 5);
		addView(icon, layoutParames);
		/*
		 * 标题初始化
		 * */
		title = new TextView(context);
		int textID = attrs.getAttributeResourceValue(null, "text", 0);
		if(textID == 0) {
			//TODO
		} else {
			title.setText(textID);
		}
		title.setGravity(Gravity.CENTER_HORIZONTAL);
		addView(title, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		
	}
	
	/**
	 * 设置图标图像
	 * resid 资源ID
	 * */
	public void setImageResource(int resid) {
		icon.setImageResource(resid);
	}
	
	/**
	 * 设置图标图像
	 * drawable Drawable图像
	 * */
	public void setImageResource(Drawable drawable) {
		icon.setImageDrawable(drawable);
	}
	
	/**
	 * 设置图标标题
	 * resid 资源ID
	 * */
	public void setText(int resid) {
		title.setText(resid);
	}
	
	/**
	 * 设置图标标题
	 * text 文本
	 * */
	public void setText(CharSequence text) {
		title.setText(text);
	}
	
	/**
	 * 设置图标点击事件监听器
	 * listener 点击事件监听器
	 * */
	public void setOnIconClickListner(View.OnClickListener listener) {
		icon.setOnClickListener(listener);
	}

}
```

 

布局文件

```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<lizhen.appstore.ext.Icon
		android:id="@+id/icon"
		src="@drawable/icon"
		text="@strings/android"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"/>
</LinearLayout>
```