如何使用意图获取所选图像的照片路径?

问题描述 投票:0回答:0

我之前发布了一个问题,我选择的图像没有重新渲染,认为它与我的适配器/数据类有关,但是在从我的可绘制文件夹中插入图像后,确定这不是问题,而是我的 initializeAddButton( ) 在我的主要活动类中运行。这是有问题的代码:

 private val lnoun =  mutableListOf<NounViewHolder>()    
    lateinit var adapter: NounAdapter
 var buttons: ArrayList<ImageButton> = ArrayList<ImageButton>(0)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val recyclerViewnouns = findViewById<RecyclerView>(R.id.recyclerViewnouns)
     //set the recycler view to a gridlay out
      recyclerViewnouns.layoutManager = GridLayoutManager (this,2)
     // sets each recylcer view to each adapter class array element
      val context: Context = applicationContext
      var img: ImageButton = ImageButton(applicationContext)
     val fab: FloatingActionButton = findViewById<FloatingActionButton>(R.id.fab)
     adapter = NounAdapter(lnoun)
      fab.setOnClickListener {
         img = initializeAddButton()
         recyclerViewnouns.layoutManager = GridLayoutManager (this,2)
       recyclerViewnouns.adapter = adapter
       lnoun.add(NounViewHolder(R.drawable.cat))
        println("Turtle tester who is getting fired Friday ${lnoun.size}")

      }


    recyclerViewnouns.adapter = adapter

    preloadDictionary()
    println("Turtle tester who is getting fired monday ${lnoun.size}")        // sets 
    each recylcer view to each adapter class array element
      }


          
         private fun initializeAddButton(): ImageButton {
        val img = ImageButton(applicationContext)
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)

          intent.setDataAndType(Uri.parse("content://" + "/sdcard/Download/image.jpg"), 
       "*/*");
        val result = 1
       // I think this line is the trouble. I can't seem to get the path of my selected 
       // image
        val photoPath = intent.data?.path

        val bitmap1 = BitmapFactory.decodeFile(photoPath)

        // Uri photoURI = FileProvider.getUriForFile(context, 
     context.getApplicationContext().getPackageName() + ".provider", createImageFile());

        img.setImageBitmap(bitmap1)
        
    startActivity(intent)


    return img

}
}

98% 确定这一行是我函数中的故障代码。正如我所说,我不认为它会影响这张图片的路径:

val photoPath = intent.data?.path

如何编辑这行代码,以便它获取我选择的意图图像的路径。

android android-studio kotlin android-intent photo
© www.soinside.com 2019 - 2024. All rights reserved.