访问ImageAdapter中的XML Image Array

时间:2016-11-15 12:10:36

标签: arrays android-studio gridview baseadapter typed-arrays

我的问题与this thread非常相似,但从未得到妥善回答。 我有一个ImageAdapter设置;

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;

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

在我的MainActivity类中,我试图获取图像数组并将其传递给ImageAdapter,但我不能;

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

我目前收到错误消息:

  

引起:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.content.res.Resources android.content.Context.getResources()'

我的应用在加载时崩溃了。我想在我的GridView中使用我的ImageAdapter显示图像。

1 个答案:

答案 0 :(得分:0)

尝试使用

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

而不是

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