How to populate a gridView using an ImageAdapter with a drawable array stored in xml

廉价感情. 提交于 2019-12-24 00:05:12

问题


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.

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.

The array:

<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>

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 };
}

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


回答1:


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




回答2:


I think this is the thread which is similar to your question. please check this.

Here they used custom array of drawables. you can try your resource drawable array in place of it



来源:https://stackoverflow.com/questions/13577125/how-to-populate-a-gridview-using-an-imageadapter-with-a-drawable-array-stored-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!