Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save EmmanuelGuther/1fde5cfbd1cdcd21cd852e3bb5716e02 to your computer and use it in GitHub Desktop.
Save EmmanuelGuther/1fde5cfbd1cdcd21cd852e3bb5716e02 to your computer and use it in GitHub Desktop.
An example to how implements a button Onclick in Kotlin - Android Fragment
class ExmpleFragment : Fragment(), View.OnClickListener {
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater!!.inflate(R.layout.fragment, container, false)
val btn: Button = view.find(R.id.button2)
btn.setOnClickListener(this)
return view
}
companion object {
fun newInstance(): ExampleFragment {
return ExampleFragment()
}
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.button2 -> {
toast("alpjasjdkasndknaskdnkasndkasndkjnaskjdnaskjdnkasjndkas")
}
else -> {
}
}
}
}
@avazquezpr
Copy link

Wow! Just what I needed. Thanks for this!!! 👍

@Smahrt
Copy link

Smahrt commented Apr 4, 2018

You my friend, are a life saver!

@matheustsa
Copy link

else is like "default"?

@lovekothari123
Copy link

lovekothari123 commented Jun 11, 2018

[](if i will put one constructor in side this:- like that

open class First : Fragment() {

// constructor(contex: Context) : super(contex)
}
kotline_fragment))

how can i solve this problem
can you plz help me for that

@Billkyriaf
Copy link

It gives me an erron in btn.setOnClickListener(this) saying Required: View.OnClickListener! Found class Fragment

@MarioIoannou
Copy link

Lifesaver!!!!

@Pikl6000
Copy link

Thank you so much !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment