我正在阅读开始Android 4开发,在第5章中,它谈到了Gallery和ImageVievs,并介绍了声明样式的XML标签,但没有解释其目的。我也试图在参考上找到一些信息,但没有运气。例如,我们有以下内容:
res/values/attrs.xml
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
<declare-styleable name=”Gallery1”>
<attr name=”android:galleryItemBackground” />
</declare-styleable>
</resources>
示例.java
public class GalleryActivity extends Activity {
[...]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
[...]
}
[...]
public class ImageAdapter extends BaseAdapter {
[...]
int itemBackground;
public ImageAdapter(Context c) {
context = c;
//---setting the style---
TypedArray a = obtainStyledAttributes(
R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
[...]
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
我已经阅读了几次代码,但我真的不明白定义这个可样式的 Gallery1 的目的,只有一个 attr 子级,只有一个 name 属性。. 你能帮我吗?这个galleryItemBackground是系统提供的东西还是我们定义的东西?我们在这段代码中做什么?
提前感谢您的任何帮助!
此标签是 R.Styleable
中定义的一组预制 Android 属性的一部分,这些属性可以从属性名称之前的 android:
xml 命名空间前缀中区分自定义样式标签。
此特定属性描述为:
库项的首选背景。这应该设置为 您从适配器提供的任何视图的背景。
但是,您是对的,自定义属性标记不仅需要属性的名称,还需要其类型,例如,将自定义元素添加到attrs.xml
文件中可能如下所示:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomView">
<attr name=”android:galleryItemBackground” />
<attr name="myCustomAttr" format="string" />
</declare-styleable>
</resources>
请注意,第二个属性上也缺少 android:
命名空间。
编辑:
是否有任何官方文档页面对此进行了深入解释 风格?
查看R.attr
(点击链接)了解 Android 中包含的各种属性。 您不需要为它们声明类型,因为它们都已声明。 若要了解为特定属性声明的类型,请查找您感兴趣的属性的说明。 如您所料,galleryItemBackground
是对另一个资源的引用;其他可能性是布尔值、浮点数、颜色等。
其他参考:Andtoid使用<declare-styleable>
标签创建AttributeSet
。 TypedArray
用于解析AttributeSet
。
如果上面代码的目的 [...] 只是获取默认值 视图背景的可绘制对象,我无法设置变量吗 itemBackground with getDrawable(android.R.attr.galleryItemBackground)?
在示例中,当只有一个属性时,很难看到此模式的有用性。 你可以按照你的要求去做,这可能会更容易。 然而,该结构是Android口头禅的一部分,它将UI的"外观"与其"功能"分开,允许您在xml中设置某些属性,而不必在代码中执行所有操作。 以View
课为例。 它具有 30 多个可以在 xml 文件中设置的属性(大小、填充、可单击、可聚焦等);创建自定义子View
类的人可以在 XML 中设置这些属性中的一些、全部或不设置,并在创建视图时自动为您处理这些属性。 如果需要,有一些代码等效项可以设置属性,但是想象一下,每次子类化时View
都必须在代码中设置所有属性,而不是可以选择在 xml 中设置它们。
只为执行完全相同操作的类创建自己的资源也是一件小事,但是如果您不覆盖它们,使用内置样式将提供与 Android 框架的外观和感觉相匹配的默认资源。
希望这有帮助。