Reputation: 8042
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
Upvotes: 9
Views: 8395
Reputation: 9478
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 */}
}
Upvotes: 21
Reputation: 69709
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
}
Upvotes: 4