Search code examples
androidkotlinandroid-fragmentstoast

KOTLIN not Java! How to use maketoast within a fragment (or make a click work in a fragment)


Hi I've been having issue with making a click work in a fragment. (e.g. Toast, button, or anything related to click)

For instance, I'm trying to implement Toast.makeText in the code below. xml file mentioned in this code is an image gallery and I want my app to display a toast for each image to show what the image is about.

I've been trying many different things and have been searching for 10 hourish, but nothing seemed to work. Plus, most sources related to this question were for Java only. Any help or suggestion will very much be appreciated.

class GalleryFragment : Fragment(), View.OnClickListener {
    var myButton: ImageView? = null
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val myView: View = inflater.inflate(R.layout.fragment_gallery, container, false)
        myButton = myView.findViewById<View>(R.id.image1) as ImageView
        myButton!!.setOnClickListener(this)
        return myView
    }
    override fun onClick(v: View) {
        Toast.makeText(activity?.applicationContext, "Beach", Toast.LENGTH_SHORT).show()
    }
    
}

Solution

  • Your code looks Ok.

    Please check if the image on which you are expecting the click to show a toast is not too small that it is not physically clickable. maybe you have the image view of the size 16dp or even less. Or you may have set the android:clickable to false.

    If you could add the layout file, it would be easier to find the issue.