Android自定义控件

下面的例子就来自定义一个简单的Button:

首先是布局,


    <LinearLayout
        android:id="@+id/bottom_layout"
        android:layout_width="fill_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal"
        android:paddingBottom="3dp"
        android:paddingTop="3dp" 
        android:background="@drawable/bg_home_bottom_bar">

	<com.mybutton.utils.widgets.HomeBottomButton
            android:id="@+id/home_bottom_button_quickcall"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:gravity="center"
            quickcall:home_bottom_button_icon="@drawable/icon_home_button_quick_call"
            quickcall:home_bottom_button_text="@string/home_bottom_quick_call" />



在res/values文件下定义一个attrs.xml文件,代码如下:


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="HomeBottomButton">
        <attr name="home_bottom_button_icon" format="integer"></attr>
        <attr name="home_bottom_button_text" format="string"></attr>
    </declare-styleable>
</resources>






然后实现一个新的控件,

/**
 * Copyright (C) 2013, Easiio, Inc.
 * All Rights Reserved.
 */




import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * HomeBottomButton
 * 
 */
public class HomeBottomButton extends RelativeLayout {
	private static final String TAG = "[ZHUANG]HomeBottomButton";
	
	public HomeBottomButton(Context context) {
		super(context);
	}
	
	public HomeBottomButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(attrs, context);
	}

	protected void initView(AttributeSet attrs, Context context) {
		inflate(context, R.layout.home_bottom_button_layout, this);
		setClickable(true);
		setFocusable(true);
		Drawable	drawable	= null;
		String		textValue	= null;
		if (attrs != null) {
			//在自定义组件中TypedArray,可以如下获得xml中定义的值:
			final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.HomeBottomButton);
			drawable	= a.getDrawable(R.styleable.HomeBottomButton_home_bottom_button_icon);
			textValue	= a.getString(R.styleable.HomeBottomButton_home_bottom_button_text);
			a.recycle();

			if (LogLevel.DEV) {
				DevLog.d(TAG, "Init, textValue " + textValue);
			}
		}

		((ImageView) findViewById(R.id.home_bottom_button_image)).setImageDrawable(drawable);;
		((TextView) findViewById(R.id.home_bottom_button_text)).setText(textValue);;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值