Issue
I want to know how to add multiple click events to buttons defined in XML, as previously, in Java, we implemented View.onClickListener
interface and did the rest of the work in onClick
method.
Example:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.oneButton:
// do your code
break;
case R.id.twoButton:
// do your code
break;
case R.id.threeButton:
// do your code
break;
default:
break;
}
}
I'm making a basic calculator app with the new Kotlin but it seems Kotlin has no such provisions, instead my code looks too long and verbose, as I'm attaching events to all buttons individually.
Can someone tell me how to do the same way in Kotlin? Thanks
Solution
First of all implement OnClickListener
in your Activity
, like
class MainActivity : Activity , OnClickListener
then override its implementation like
func onClick(v:View) {
//use when here like
case R.id.youview -> {
// do your work on click of view
}
Don't forgot to set clicklistener on your View
.
yourView.setOnClickListener(this)
Or for better understanding go step by step -
Implement
OnClickListener
in yourActivity
.Compiler will ask you to implement overrided methods. Implement those.
Copy paste your java code which you wrote inside
onClick
method, that can be converted by kotlin itself or write downwhen
conditions.
Answered By - Rahul
Answer Checked By - Mary Flores (JavaFixing Volunteer)