无法从Activity

时间:2019-02-27 07:51:54

标签: android android-fragments android-activity kotlin onactivityresult

我的活动流程是这样的。

Fragment A中,它允许用户捕获图像,并且图像将显示在Activity B上,以便用户进行一些编辑。

片段A

mImageListAdapter.mAddImageClickListener = object : ImageListAdapter.AddImageClickListener {
            override fun addImageClicked() {
                val options = arrayOf<CharSequence>("Take Photo", "Choose From Gallery", "Cancel")
                val builder = android.support.v7.app.AlertDialog.Builder(activity)
                builder.setTitle("Select Option")
                builder.setItems(options) { dialog, item ->
                    if (options[item] == "Take Photo") {
                        dialog.dismiss()
                        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                        startActivityForResult(intent, CAMERA_CAPTURE)
                    } 
                }
                builder.show()
            }
        }

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        var bitmap: Bitmap? = null
        if (requestCode == CAMERA_CAPTURE && resultCode == Activity.RESULT_OK) {
            val extras = data?.extras
            if (extras != null) {
                bitmap = extras.get("data") as Bitmap
                val intent = Intent(activity, ActivityB::class.java)
                intent.putExtra("bitmap", bitmap)
                startActivityForResult(intent, 12)
            }
        } else if (requestCode == 12 && resultCode == Activity.RESULT_OK) {
            longToast("It get result from Activity B")
        } else {
            longToast("Nothing")
        }
    }

在活动B中,单击完成按钮后,编辑后的图像应该返回到片段A,我希望在其中显示“ It get result from Activity B”,但什么都不会显示

活动B

doneBtn.setOnClickListener {
            image.buildDrawingCache()
            val bitmap = image.getDrawingCache()
            val resultIntent = Intent()
            resultIntent.putExtra("bitmap", bitmap)
            setResult(Activity.RESULT_OK, resultIntent)
            finish()
        }

2 个答案:

答案 0 :(得分:0)

作为最简单的选项之一,它会通过静态变量传递

在片段A中创建一个静态字段

    companion object {
        public var globalBitmap: Bitmap? = null
    }

并在onActivityResult方法的片段A中将位图保存到静态变量中

...
    if (requestCode == CAMERA_CAPTURE && resultCode == Activity.RESULT_OK) {
                val extras = data?.extras
                if (extras != null) {
                    globalBitmap = extras.get("data") as Bitmap

                    startActivityForResult(intent, 12)
                }
            }
...

在活动B中,从Fragment A静态变量中读取结果位图

FragmentA.globalBitmap

答案 1 :(得分:0)

看到我快速尝试并添加了一个断点,并收到了片段中的回调。

enter image description here使用 上下文

 val builder = android.support.v7.app.AlertDialog.Builder(context)

代替了 活动

 val builder = android.support.v7.app.AlertDialog.Builder(activity)