首页 > 解决方案 > Kotlin Android:将位图分配给 Imageview

问题描述

我正在使用 Kotlin 前端/Python 后端构建一个应用程序。我的 python 脚本在 getFilesDir() 目录 (/data/user/0/com.example.inprogress/files/mygraph.png) 下创建一个 .png 文件。然后我想使用 kotlin 来获取 .png 文件并将其显示在 imageview 上。

在此处输入图像描述

我的目标是将位图值分配给我的 imageview id graphId。

我使用下面的代码,但我得到了空白的 imageview 而不是我想要显示的 .png 文件。请注意,我没有收到任何错误消息。我在哪里做错了?

class GraphRes : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_graphres)

        var data = intent.extras
        var graph = data!!.get("res").toString()
        // graph is where the .png file is stored
        // graph: /data/user/0/com.example.inprogress/files/mygraph.png


        var graphId = ImageView(this)
        graphId.setImageBitmap(BitmapFactory.decodeFile(graph))

    }
}

标签: androidkotlinbitmapandroid-bitmap

解决方案


你有READ_EXTERNAL_STORAGE权限吗?

如果你有它并且它仍然不起作用,请尝试以下方法:

graphId.setImageURI(Uri.fromFile(File(graph)));

或者您也可以使用 Glide 库来显示您的图像,它会有效地做到这一点。


推荐阅读