skip to Main Content

I have a small app, where i have a fragment AchievementFragment and in there i have a few imageButtons. I want to make it so that when i click on one of them, a toast appears on the screen, but i have a problem with just the imageButton itself. I tried following a few online tutorials like this one: https://www.geeksforgeeks.org/imagebutton-in-kotlin/, but when i try to use

val imgbtn = findViewById<ImageButton>(R.id.imageBtn)

i get unresolved findViewById reference error.

2

Answers


  1. You can’t use directly findViewById in fragments, you have to use it with root view, in your onCreateView you are returning the root view. Your other views are inside the root view. So if you want to access a view inside root you should use like this before returning the root view

     override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.fragment_blank, container, false)
    
        val imgbtn = root.findViewById<ImageButton>(R.id.imageBtn)
        
        return root
    }
    
    Login or Signup to reply.
  2. val imgbtn = (activity as "activity name").findViewById<ImageButton>(R.id.imageBtn)
    

    replace "activity name" with your activity.

    OR

    Use View Binding instead of findViewById.
    https://developer.android.com/topic/libraries/view-binding

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search