天天看點

由淺入深學習自定義控件(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這個名稱空間。

繼續閱讀