简体   繁体   中英

Android kotlin - Unresolved reference for setImageBitmap in fragment

I just try to set a Bitmap inside an ImageView in fragment:

imageLeft.setImageBitmap(duelbildBitmap)

and get Unresolved reference for setImageBitmap

Why? It works in activity

Thanks in advance

You can not just use R.id.imageView , because that is integer id not the ImageView object. So it can not find setImageBitmap() method on Integer .

You have two ways

1: by using findViewById()

class GalleryFragment : Fragment() {
    private lateinit var viewOfLayout: View
    private lateinit var imageView: ImageView

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        viewOfLayout = inflater.inflate(R.layout.fragment, container, false)
        return viewOfLayout
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        imageView = view.findViewById(R.id.imageView)
        imageView.setImageBitmap(bitmap) // set bitmap anywhere
    }
}

2: by using kotlinx.android.synthetic

class GalleryFragment : Fragment() {
    private lateinit var viewOfLayout: View
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        viewOfLayout = inflater.inflate(R.layout.fragment, container, false)
        viewOfLayout.imageView.setImageBitmap(bitmap) // set bitmap anywhere
        return viewOfLayout
    }
}

If imageView is not imported automatically in this case, then import manually.

import kotlinx.android.synthetic.main.fragment.view.*

In second method you have to apply plugin apply plugin: 'kotlin-android-extensions' if not applied at the end of app level build.gradle file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM