1

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

1 Answers1

3

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.

Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212