Android Fragments 如何从图片库中提取图片片段?

aurhwmvo  于 2023-01-13  发布在  Android
关注(0)|答案(1)|浏览(137)

我想做一个片段的功能,当我点击按钮,画廊将打开,然后我选择一个图像,该图像将被放入我的imageview。
这是我写的代码:

class PostFragment : Fragment(R.layout.fragment_post) {

    companion object{
        val IMAGE_REQUEST_CODE = 100
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View{
        val rootView: View = inflater.inflate(R.layout.fragment_post, container, false)

        var ButtonChooseImage: Button = rootView.findViewById(R.id.button_choose_image)
        var postImage: ImageView = rootView.findViewById(R.id.postImage)
        ButtonChooseImage.setOnClickListener{
            openFileChooser()
        }
        return rootView
    }

    private fun openFileChooser() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/*"
        startActivityForResult(intent, IMAGE_REQUEST_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val rootView: View = layoutInflater.inflate(R.layout.fragment_post,null)
        var postImage: ImageView = rootView.findViewById(R.id.postImage)

        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK){

            postImage.setImageURI(data?.data)
        }
    }
}

一切正常,除了图像没有显示在ImageView中。(在我按下按钮画廊弹出后,我选择了一张图像,但它没有显示在ImageView中。)
我哪里错了?请告诉我。

gorkyyrv

gorkyyrv1#

问题是你正在第二次膨胀视图。你正在做的是创建一个新的布局,你看不见,你在那里发布你的图像。
有很多解决方法。比如你可以试试,

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    val postImage: ImageView = view.findViewById(R.id.postImage) // <--------

    if (requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK) 
        postImage.setImageURI(data?.data)
    else super.onActivityResult(requestCode, resultCode, data)
}

或者,

lateinit var postImage: ImageView // <--------

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    val rootView: View = inflater.inflate(
        R.layout.fragment_post, container, false)

    postImage = rootView.findViewById(R.id.postImage) // <--------

    rootView.findViewById<Button>(R.id.button_choose_image)
        .setOnClickListener{ openFileChooser() }
    return rootView
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        
    if (requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK) 
        postImage.setImageURI(data?.data)
    else super.onActivityResult(requestCode, resultCode, data)

}

或其他方式,如ViewBinding

相关问题