1

这听起来可能很愚蠢,但我无法理解它。

我有一个自定义 ListAdapter,它用我的模型构建的图像、文本和其他内容填充行。现在我希望当您单击该列表中的(任何)图像时,相机将打开并且用户应该能够拍照,然后单击的图像应该显示使用相机拍摄的照片。得到它?

现在在适配器中我只是做这样的事情:

public View getView(int position, View convertView, ViewGroup parent) {
    ...stuff...
    ImageView image = (ImageView) elementView.findViewById(R.id.element_image);
    image.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            ((Activity) context).startActivityForResult(takePicture, 0);
        }
    ...other stuff...
});

我为每个 ImageView 添加了一个 onClick 选项,可以打开相机并让用户拍照。问题是上下文(我的 MainActivity)在方法“onActivityResult”上获得了回调,但我怎么知道哪个回调属于哪个 ImageView?

 protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)

是否可以在意图内发送参考?或者它应该如何知道哪个意图调用属于哪个 ImageView?

我希望你能理解我的问题。否则就问吧。先感谢您 ;)

4

1 回答 1

2

一个快速简便的解决方案是将position您的 存储ListAdapterSharedPreference. 在 youonActivityResult中,您可以SharedPreference再次提取它,以了解请求的是哪一个:

@Override
public void onClick(View v) {

    // Store in shared preferences
    SharedPreferences sharedPref = getSharedPreferences("FileName",MODE_PRIVATE);
    SharedPreferences.Editor prefEditor = sharedPref.edit();
    prefEditor.putInt("position_in_adapter",position);
    prefEditor.commit();

    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    ((Activity) context).startActivityForResult(takePicture, 0);
}

而不是你的活动结果:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent){

    SharedPreferences sharedPref = context.getSharedPreferences("FileName",MODE_PRIVATE);

    // Extract again
    int position= sharedPref.getInt("position_in_adapter", -1);
}

编辑:另一种选择是使用您的 requestCode 作为您的职位。例如

startActivityForResult(takePicture, position);

并在您的 onActivityResult 中再次提取它:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent){
    // requestCode is the position in your adapter
}
于 2013-04-02T20:22:47.713 回答