下面的例子就来自定义一个简单的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);;
}
}