【问题标题】:How to find out what intent callback reference to what如何找出什么意图回调引用了什么
【发布时间】:2013-03-24 07:21:42
【问题描述】:

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

我有一个自定义的 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)

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

我希望你能理解我的问题。否则就问吧。提前谢谢你;)

【问题讨论】:

    标签: android list android-intent camera adapter


    【解决方案1】:

    一个快速简单的解决方案是将positionListAdapter 存储在SharedPreference 中。在您的onActivityResult 中,您可以再次提取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
    }
    

    【讨论】:

    • 好主意,但没有简单的解决方案吗?这更像是一个黑客。
    • 您也可以使用 requestCode 来回传递您的位置。见编辑。我认为您不能将其作为参数添加到您的意图中,因为您无法控制相机应用程序返回的意图
    • @StupidBird 不是 hack,这就是 android 的工作原理:) 在活动之间传递意图、parcelables、捆绑包。
    • @t0mm13b 好吧,您必须同意这不是真正干净的代码;)我们没有“更好”的解决方案是有原因的吗?就像在意图中传递引用或重定向回调(大声笑)或包装器或只是更简单的东西?我简直不敢相信没有更好的解决方案。但只要我找到了别的东西,我就会坚持这个..
    • 至于 重定向回调 (lol) 不完全确定您的意思。 ;) Android 的要点是基于Intents 在活动之间传递数据。见this :)
    猜你喜欢
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多