我正在阅读“开始 Android 4 开发”,在第 5 章中讨论了Gallery和ImageVievs,并介绍了可声明样式的XML 标记,但没有解释其用途。我还试图在参考资料上找到一些信息,但没有运气。例如,我们有以下几点:
资源/值/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;
}
}
}
我已经阅读了几次代码,但我真的不明白用一个仅具有name属性的单个attr子项定义这个可样式化 Gallery1的目的。你能帮我吗?这个galleryItemBackground是系统提供的还是我们定义的?我们在这段代码中做了什么?
预先感谢您的任何帮助!