由浅入深学习自定义控件(3)-组合控件的简单例子

自定义组合控件是用已由的控件组合成一个新的控件,便于控件的重用。
整个过程可以分四步。
    第一步,定义一个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这个名称空间。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值