问题描述
我正在使用google文档中提供的示例ImageAdpater来填充带有可绘制对象的gridview.我想做的是在xml文件中用可绘制的数组填充gridview.
I am using the sample ImageAdpater provided in the google documentation to populate a gridview with drawables. What I'm trying to do is populate the gridview with an array of drawables in an xml file.
我使用 TypedArray imgs = getResources().obtainTypedArray(R.array.log_type_icons);
从我的主要活动中访问数组,但是在ImageAdapter类中不起作用.
I use TypedArray imgs = getResources().obtainTypedArray(R.array.log_type_icons);
to access the array from my main activity, but that doesn't work within the ImageAdapter class.
数组:
<string-array name="log_type_icons">
<item>@drawable/ic_launcher</item>
<item>@drawable/ic_headache</item>
<item>@drawable/ic_man</item>
<item>@drawable/ic_woman</item>
<item>@drawable/ic_kneel</item>
</string-array>
有效的ImageAdapter:
The working ImageAdapter:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
Log.i("log tag", "gotten resources: " + mThumbIds);
if (convertView == null) { // if it's not recycled, initialize some
// attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = { R.drawable.ic_headache,
R.drawable.ic_kneel, R.drawable.ic_man, R.drawable.ic_woman,
R.drawable.ic_launcher };
}
我知道我可以手动将可绘制的引用添加到Integer数组,但是我也从我的主要活动中引用了xml数组,因此能够添加到xml而不必更改代码将是理想的选择.有人对此有见识吗?我是在做错事还是缺少明显的东西?
I know I could manually add the drawable references to the Integer array, but I reference the xml array from my main activity as well, so it would be ideal to be able to add to the xml and not have to change the code.Does anyone have any insight into this? Am I doing something wrong or missing Something obvious?
任何帮助,我们将不胜感激,谢谢
Any help would be appreciated,Thank you
推荐答案
我最终通过使用'getResources().obtainTypedArray(R.array.log_type_icons);'解决了这个问题.在我的主要活动中获取数组,然后将其传递给图像适配器,而不是在适配器中使用"getResources()"
I ended up solving this problem by using 'getResources().obtainTypedArray(R.array.log_type_icons);' to get the array in my main activity, then passed it to the image adapter instead of using 'getResources()' within the adapter
这篇关于如何使用带有存储在xml中的可绘制数组的ImageAdapter填充gridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!