Android自定義控制元件系列之基礎篇

傑瑞教育發表於2015-03-31

一、概述

在android開發中很多UI控制元件往往需要進行定製以滿足應用的需要或達到更加的效果,接下來就通過一個系列來介紹自定義控制元件,這裡更多是通過一些案例逐步去學習,本系列有一些典型的應用,掌握好了大家也可去創新開發出一些更好的UI,本次先通過簡單案例掌握一些基礎知識——如何在自定義控制元件中定義屬性.

二、實現定製一個簡單RadioButton

1、編寫型別MRadioButton 擴充套件RadioButton

public class MRadioButton extends RadioButton {
…    
}

2、在MRadioButton類中,定製屬性

我們可以在控制元件中定義自己的屬性,可以定義多個屬性,但必須封裝提供set/get方法,也就是按規範寫。如mValue屬性,像下面程式碼

private String mValue;
    public String getmValue() {
        return mValue;
    }
    public void setmValue(String mValue) {
        this.mValue = mValue;
    }

3、為定製的屬性編寫attrs.xml資源

該資原始檔放在res/values目錄下,內容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MRadioButton">
            <! – 屬性名稱-->
        <attr name="value" format="string" />
    </declare-styleable>
</resources>

4、在MRadioButton類中定義建構函式,初始化屬性

            public MRadioButton(Context context) {
        super(context);
    }
public MRadioButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
        public MRadioButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        //從attrs.xml中載入一個名字叫’ .MRadioButton’的declare-styleable資源
    TypedArray tArray = context.obtainStyledAttributes(attrs, R.styleable.MRadioButton);
        //將屬性value與類中的屬性mValue關聯
    this.mValue = tArray.getString(R.styleable.MRadioButton_value);
        //回收tArray物件
    tArray.recycle();
    }

5、在MainActivity中佈局檔案中新增MRadioButton元件,如下所示

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:jereh="http://schemas.android.com/apk/res/com.jereh. view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.zdyview.MainActivity" >

    <com.itc.zidingyiview.MRadioButton
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/mrb"
        jereh:value="hello"
        />

</RelativeLayout>

6、MainActivity程式碼:

public class MainActivity extends Activity {
    private MRadioButton rb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rb=(MRadioButton)super.findViewById(R.id.mrb);
        rb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
Toast.makeText(MainActivity.this, rb.getmValue(),Toast.LENGTH_LONG).show();
            }
        });
    }
}

當點選單選按鈕會顯示hello資訊

相關文章