尝试将图库中的图像显示为动态创建的ImageView

时间:2017-08-19 18:46:50

标签: android listview android-intent

我试图显示我从图库中获取的图像。我不能像通常那样打电话给setImageBitmap。那是因为还没有创建ImageView吗?

公共类MainActivity扩展了AppCompatActivity {

int RESULT_LOAD_IMAGE = 1;


//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<ImageView> listItemImg=new ArrayList<>();

//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LIST VIEW
ArrayAdapter<ImageView> adapter;

//RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
int clickCounter=0;
private ListView mListView;

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


    if (mListView == null) {
        mListView = (ListView) findViewById(R.id.picsListView);
    }

    adapter = new ArrayAdapter<>(this, R.layout.item_layout, R.id.picImageView, listItemImg);

    setListAdapter(adapter);

}

这是单击按钮时调用的方法。

public void addStuff(View view) {

    Intent gallery = new Intent(Intent.ACTION_GET_CONTENT);
    gallery.setType("image/*");
    startActivityForResult(gallery, RESULT_LOAD_IMAGE);

}


//METHOD WHICH WILL HANDLE DYNAMIC INSERTION


protected ListView getListView() {
    if (mListView == null) {
        mListView = (ListView) findViewById(R.id.picsListView);
    }
    return mListView;
}

protected void setListAdapter(ListAdapter adapter) {
    getListView().setAdapter(adapter);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
        Uri imageUri = data.getData();
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);

            //This is the ImageView in which I'm trying to display the selected Image.
            listItemImg.set(clickCounter, bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }

        clickCounter++;
        adapter.notifyDataSetChanged();
    }
}


}

很抱歉,如果问题太基础了。我无法找到任何无处使用的例子。

1 个答案:

答案 0 :(得分:0)

您正在为ListView设置错误的适配器。如果直接使用ArrayAdapter,则只能将给定数组中相应的 String 对象放置到 TextViews

在这种情况下,您需要通过扩展ArrayAdapter (或任何适配器)来生成自定义适配器,并使用getView(int, View, ViewGroup)方法。

Here是一个关于Adapters和AdapterViews的好教程。