我正在阅读《Beginning Android 4 Development》,第5章中谈到了Gallery和ImageViews,并引入了declare-styleable XML标签,但没有解释其目的.. 我也在参考资料中试图找到一些信息,但没有成功..例如我们有以下内容:
res/values/attrs.xml
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
<declare-styleable name=”Gallery1”>
<attr name=”android:galleryItemBackground” />
</declare-styleable>
</resources>
example.java
->example.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 的可样式化对象时,只使用一个带有 name 属性的 attr 子元素的目的是什么。你能帮帮我吗?这个 galleryItemBackground 是系统提供的还是我们自己定义的?在这段代码中,我们在做什么?
非常感谢您提供的任何帮助!
<attr name=”android:galleryItemBackground” />
到底对 styleable MyCustomView 是在说什么呢?它是在说:你有一个属性 galleryItemBackground,其值与 android:galleryItemBackground 相同吗?很抱歉,但我读得越多,就越感到困惑 O_o - Gianni Costanzi