Tôi nghĩ rằng nó sẽ được tốt hơn để sử dụng nó như một tài liệu tham khảo đơn giản:
<declare-styleable name="TCButton">
<attr name="customText" format="string"/>
<attr name="backgroundImage" format="reference" />
</declare-styleable>
Và đặt nó trong xml của bạn như thế này:
<your.package.name.TCButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:customText="Some custom text"
custom:backgroundImage="@drawable/myImage"
/>
Và trong lớp học của bạn thiết lập các thuộc tính như này:
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: Đừng quên thêm dòng này cho phần tử gốc của bố cục bạn đang sử dụng chế độ xem tùy chỉnh của mình trong
xmlns:custom="http://schemas.android.com/apk/res-auto"
Nếu bạn không đặt, bạn sẽ không thể truy cập thuộc tính tùy chỉnh của mình.
Nguồn
2014-08-06 10:50:10
xem lại điều này, có thể thêm rằng khai báo không gian tên bị lỗi sẽ không cung cấp lỗi thời gian biên dịch. Trong ví dụ này, nó có thể trông giống như 'xmlns: myapp =" http://schemas.android.com/apk/res/se.jog.mob "' nếu 'lớp MyLayout' được khai báo trong' se.jog.mob' . – JOG
Bạn nên gọi 'a.recycle()' khi bạn sử dụng các thuộc tính được tạo kiểu. – karl
Trong các dự án gradle, lược đồ tùy chỉnh phải luôn là "http://schemas.android.com/apk/res-auto" –