如何将图像视图从改造加载的片段传递给子片段?

时间:2021-02-13 01:46:56

标签: android kotlin android-fragments fragment pass-data

所以我有 1 个主片段和 2 个 childfragmnet,我想将图像视图从主片段传递到 childfragment,而无需在该 2 个 childfragment 中再次进行 Get Request 改造,该怎么做??

我已经在我的主要 Fargment 中尝试过这个:

private lateinit var imgFile: File

......

intent.putExtra("resId", imgFile)

然后在子片段中调用它:

val bundle: Bundle = intent.extras
    val resId: Int = bundle.getInt("resId")
    binding.imgmainac.setImageResource(resId)

2 个答案:

答案 0 :(得分:0)

你总是可以直接从子片段直接访问你的父片段字段

试试这个

(parentFragment as MainFragment).imgFile

答案 1 :(得分:0)

你在这里混淆了两件事:

  • resId 只是一个标识内部应用资源的 Int。
  • 一个文件

文件不是 resId 或 Int。

所以如果你已经有一个文件,我建议:

  • 将文件 URI 作为字符串放入包中(可以使用 file.toURI().toString() 获取)
  • 使用 Uri.parse(bundle.getString(...)) 检索它
  • 使用 .setImageURI(...) 在 ImageView 上设置它

编辑:

总结一下:

发送方结束

    intent.putExtra("imageUri", file.toURI().toString())

在接收端

    val bundle = intent.extras
    val imageUri = bundle?.getString("imageUri")?.let { Uri.parse(it) }
    imageView.setImageURI(imageUri)