本文介绍了在ImageAdapter中访问XML图像数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与此线程,但从未得到正确回答.我有一个ImageAdapter设置;

My question is very similar to this thread, however it was never properly answered.I have an ImageAdapter setup as so;

public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    int[] mImages;

    public ImageAdapter(Context c, int[] images) {
        mContext = c;
        mImages = images;
    }

    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
        } else {
            imageView = (ImageView) convertView;
        }
        imageView.setImageResource(mImages[position]);
        return imageView;
    }
}

我希望图像来自XML;

And I want the images to be from an XML;

<integer-array name="images">
    <item>@drawable/image1</item>
    <item>@drawable/image2</item>
    <item>@drawable/image3</item>
</integer-array>

在我的MainActivity类中,我尝试获取图像数组并将其传递到ImageAdapter中,但是我做不到;

In my MainActivity class I have tried to get the image array and pass it into the ImageAdapter but I can't;

public class MainActivity extends AppCompatActivity {
    private int images[] = getResources().getIntArray(R.array.images);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GridView gridview = (GridView) findViewById(R.id.gridView);
        gridview.setAdapter(new ImageAdapter(MainActivity.this, images));
    }
}

我当前收到一条错误消息:

I am currently getting an error message:

我的应用程序在加载时崩溃了.我想让我的ImageAdapter在GridView中显示来自XML的图像.

with my app crashing on load up. I want to make my ImageAdapter display images from an XML in my GridView.

推荐答案

尝试使用

 private int images[] = {R.drawable.image1, R.drawable.image3, R.drawable.image3};

代替

 private int images[] = getResources().getIntArray(R.array.images);

这篇关于在ImageAdapter中访问XML图像数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-18 16:00