Home > database >  setOnClickListener not working in fragment in kotlin
setOnClickListener not working in fragment in kotlin

Time:01-04

I am try to call my imageid in fragment class but its show error and also show error in setOnClickListener. I am try every think please if you have any answer then please share it.

//This is a code

class Home : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    val view: View = inflater!!.inflate(R.layout.fragment_home, container, false)

    view.Notification.setOnClickListener { view ->   //Notification is a id of imageView
        Log.d("btnSetup", "Selected")
    }

    return view
}

}

CodePudding user response:

To get a view from an id you need to call findViewById. In your case:

view.findViewById<View>(R.id.Notification).setOnClickListener { view ->
    Log.d("btnSetup", "Selected")
}

CodePudding user response:

The best way is to do in onViewCreated as follow:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    view.findViewById<ImageView>(R.id.Notification).setOnClickListener { view -> 
        Log.d("btnSetup", "Selected")
    }
}
  • Related