自定义组合控件是用已由的控件组合成一个新的控件,便于控件的重用。
整个过程可以分四步。
第一步,定义一个layout,实现按钮内部的布局。(当然也可以不要这一步,而选择在代码中去定义控件的方式)
第二步,继承ViewGroup或其子类实现自己的控件,在构造方法中用布局文件填充视图,并控制其中的子控件。
第三步,以完整类名的方式在activity布局文件中使用即可。
下面是一个简单的例子,首先是布局文件, 一切从简
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageButton
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/btn_star" >
</ImageButton>
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="xx" >
</TextView>
</LinearLayout>
再看实现控件的类, 使用LinearLayou做为父类
public class ImageBtnWithText extends LinearLayout {
private ImageButton mBtn;
private TextView mTv;
public ImageBtnWithText(Context context) {
this(context, null);
}
public ImageBtnWithText(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.imagebtn_withtext, this,
true);
mTv = (TextView) findViewById(R.id.text1);
mBtn = (ImageButton) findViewById(R.id.btn1);
TypedArray ta = context.obtainStyledAttributes(attrs,
R.styleable.ImageBtnWithText);
CharSequence text = ta
.getText(R.styleable.ImageBtnWithText_android_text);
if (text != null) {
mTv.setText(text);
}
System.out.println(text);
Drawable drawable = ta
.getDrawable(R.styleable.ImageBtnWithText_android_src);
if (drawable != null) {
mBtn.setImageDrawable(drawable);
}
ta.recycle();
}
public void setButtonImageResource(int resId) {
mBtn.setImageResource(resId);
}
public void setTextViewText(String text) {
mTv.setText(text);
}
}
这里setButtonImageResource与setTextViewText两个方法可以通过代码方式控件子控制的显示,构造方法中使用TypedArray 去获取xml中的属性,设置子控件,则还需要一个attrs文件。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MRadioButton2">
<attr name="value" format="string" />
</declare-styleable>
<declare-styleable name="View2">
<attr name="textColor" format="color"></attr>
<attr name="textSize" format="dimension"></attr>
</declare-styleable>
<declare-styleable name="ImageBtnWithText">
<attr name="android:text" />
<attr name="android:src" />
</declare-styleable>
</resources>
因为是已有的属性,可以直接使用android这个名称空间。