【Android】创建自定义复合控件

 

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

 

创建复合控件的步骤:

 

  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>
 
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值