我認爲這將是更好地使用它作爲一個簡單的參考:
<declare-styleable name="TCButton">
<attr name="customText" format="string"/>
<attr name="backgroundImage" format="reference" />
</declare-styleable>
,並將其設置在你的XML是這樣的:
<your.package.name.TCButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:customText="Some custom text"
custom:backgroundImage="@drawable/myImage"
/>
而在你的類中設置類似的屬性這樣的:
public TCButton(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MembershipItemView, 0, 0);
String customText;
Drawable backgroundImage;
try {
customText = a.getString(R.styleable.TCButton_customText);
backgroundImage = a.getDrawable(R.styleable.TCButton_backgroundImage);
} finally {
a.recycle();
}
if(!TextUtils.isEmpty(customText)) {
((TextView)findViewById(R.id.yourTextView)).setText(customText);
}
if(null != backgroundImage) {
((ImageView)findViewById(R.id.yourImageView)).setBackgroundDrawable(backgroundImage);
}
}
PS: 不要忘了添加此行的您使用自定義視圖的佈局的根元素
xmlns:custom="http://schemas.android.com/apk/res-auto"
如果您未設置此選項,將無法訪問您的自定義屬性。
再看一遍,可以補充說錯誤的名稱空間聲明不會給編譯時錯誤。在本例中,如果'class MyLayout'在'se.jog.mob'中聲明,它可能看起來像'xmlns:myapp =「http://schemas.android.com/apk/res/se.jog.mob」' 。 – JOG 2011-10-31 17:29:30
完成使用樣式屬性後,應該調用'a.recycle()'。 – karl 2013-06-28 17:39:12
在gradle項目中,自定義模式應始終爲「http://schemas.android.com/apk/res-auto」 – 2014-07-28 12:02:27