Creating a View Class
在Android中使用Custom View,必須尊崇以下規則
- 符合Android的標準
- Provide custom styleable attributes that work with Android XML layouts
- Send accessibility events
- 相容於其他安卓平台
Subclass a View
為了讓Android Developer Tools跟你的view做互動,你必須提供最低限度的建構子並可接受Context和AttributeSet這兩項參數
class PieChart extends View {
public PieChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
Define Custom Attributes
接著新增res/values/attrs.xml
attrs.xml1 2 3 4 5 6 7 8 9
| <resources> <declare-styleable name="PieChart"> <attr name="showText" format="boolean" /> <attr name="labelPosition" format="enum"> <enum name="left" value="0"/> <enum name="right" value="1"/> </attr> </declare-styleable> </resources>
|
再到你目標的layout檔,加入xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews"
格式為:http://schemas.android.com/apk/res/[your package name]
因為我的package是com.example.customviews
,所以是http://schemas.android.com/apk/res/com.example.customviews
activity_main.xml1 2 3 4 5 6 7
| <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews"> <com.example.customviews.charting.PieChart custom:showText="true" custom:labelPosition="left" /> </LinearLayout>
|
Apply Custom Attributes
PieChart.java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| package com.yume190.customviewtest;
import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView;
class PieChart extends LinearLayout {
private String mShowText; private String mTextPos;
public PieChart(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.getTheme().obtainStyledAttributes(attrs,R.styleable.PieChart,0, 0);
try { mShowText = a.getString(R.styleable.PieChart_showText); mTextPos = a.getString(R.styleable.PieChart_labelPosition); } finally { a.recycle(); }
LayoutInflater.from(context).inflate(R.layout.piechart, this);
TextView tv1 = (TextView)findViewById(R.id.textView1); TextView tv2 = (TextView)findViewById(R.id.textView2);
tv1.setText(mShowText); tv2.setText(mTextPos); } }
|
相關連結: