As we know in Android
we are using the switch
statement to distinct the view
like below, We used to implement
View.OnClickListener
to get onClick
interface method to perform any task
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.imgBack:
///DO SOME THING HERE
break;
case R.id.btnSubmit:
///DO SOME THING HERE
break;
}
}
Same thing i am using in Kotlin
, by implement the View.OnClickListener
and getting its overrided method like below
class FeedBackActivity : AppCompatActivity(), View.OnClickListener {
override fun onClick(p0: View?) {
/// HOW CAN I USE THE SWITCH STATEMENT TO DISTINGUISH THE VIEW CLICK
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.feed_back_screen)
imgBack.setOnClickListener(this)
}
}
In above code i want to use the same switch
to distinguish the different view click. How can i archive this in Kotlin
I know there is another way to perform the click listener in Kotlin
like below
MY_VIEW.setOnClickListener {
Toast.makeText(this,"I have clicked",Toast.LENGTH_LONG).show()
}
But i want to use the same interface in Kotin
which we are using the Android
.Please help me to short out from this problem
The Kotlin language does not have any switch statement.
Inside the onClick function, we use the Kotlin when statement, which is equivalent to switch in other languages. For the onClick function to be triggered, you must register the setOnClickListener over the button with the interface using the context( this ).
Android Switch is also a two-state user interface element that is used to toggle between ON and OFF as a button. By touching the button we can drag it back and forth to make it either ON or OFF. The Switch element is useful when only two states require for activity either choose ON or OFF.
Using the android:onClick XML attribute where you just use the name of a public method with the signature void name(View v) or by using the setOnClickListener method where you pass an object that implement the OnClickListener interface.
Use the when
expression. It is the equivalent of Java's switch
. Example code:
when(view.id) {
R.id.imgBack -> {/* code goes here */}
R.id.btnSubmit -> {/* you can omit the braces if there is only a single expression */}
}
try this use when :- , when expressions in Kotlin can do everything you can do with a switch and much more.
Actually, with when you can substitute the most complex if/else you can have in your code.
for more info visit this site
when (view.id) {
R.id.home -> perform your action here
R.id.search -> perform your action here
R.id.settings -> perform your action here
else -> perform action
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With