Ví dụ về kéo ra thuộc tính tiêu chuẩn (background) trong một chế độ xem tùy chỉnh có kiểu mặc định riêng. Trong ví dụ này, chế độ xem tùy chỉnh Mật khẩuGrid kéo dài GridLayout. Tôi đã chỉ định kiểu cho PasswordGrid đặt hình nền bằng thuộc tính android chuẩn android: background.
public class PasswordGrid extends GridLayout {
public PasswordGrid(Context context) {
super(context);
init(context, null, 0);
}
public PasswordGrid(Context context, AttributeSet attrs) {
super(context, attrs, R.attr.passwordGridStyle);
init(context, attrs, 0);
}
public PasswordGrid(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
if (!isInEditMode()) {
TypedArray stdAttrs = context.obtainStyledAttributes(attrs,
new int[] { android.R.attr.background }, // attribute[s] to access
defStyle,
R.style.PasswordGridStyle); // Style to access
// or use any style available in the android.R.style file, such as
// android.R.style.Theme_Holo_Light
if (stdAttrs != null) {
Drawable bgDrawable = stdAttrs.getDrawable(0);
if (bgDrawable != null)
this.setBackground(bgDrawable);
stdAttrs.recycle();
}
}
}
Đây là một phần phong cách của tôi.xml file:
<declare-styleable name="passwordGrid">
<attr name="drawOn" format="color|reference" />
<attr name="drawOff" format="color|reference" />
<attr name="pathWidth" format="integer" />
<attr name="pathAlpha" format="integer" />
<attr name="pathColor" format="color" />
</declare-styleable>
<style name="PasswordGridStyle" parent="@android:style/Widget.GridView" >
<!-- Style custom attributes. -->
<item name="drawOff">@drawable/ic_more</item>
<item name="drawOn">@drawable/ic_menu_cut</item>
<item name="pathWidth">31</item>
<item name="pathAlpha">129</item>
<item name="pathColor">@color/green</item>
<!-- Style standard attributes -->
<item name="android:background">@drawable/pattern_bg</item>
</style>
Cùng một vấn đề tồn tại với hướng dẫn trong Chế độ xem thư viện, tôi đã thấy cách giải quyết giúp hướng dẫn hoạt động nhưng không giải thích cách hướng dẫn sẽ phải được khắc phục chỉ sử dụng các lớp SDK và không thêm lớp của riêng bạn xml với phong cách trong đó. Hướng dẫn có tại http://developer.android.com/resources/tutorials/views/hello-gallery.html mã nằm trong "ImageAdapter (Ngữ cảnh c)" Constructor – AGrunewald
Đây là thảo luận tương tự http://stackoverflow.com/q/8793183/1307690 – Lemberg