Can anyone please explain why should we use (View view
), and what does it mean in Android while defining a method.
public void dosomething(View view) {}
Thanks in advance. I'm a beginner, so my questions might seem basic.
Usually View is used as arguments in methods which act as some kind of listener.
For example when you have more than 1 Button
in your layout and you set onClickListener
on them, you create a method like this:
public void onClick(View view){
}
Here the View is the view on which the user has clicked. So if you have 2 buttons on your layout, you can check which one the user has clicked by using the following code:
public void onClick(View view){
switch(view.getId()){
case R.id.button1: //do something here
break;
case R.id.button2: //do sonething else here
break;
}
}
Hence, View
is supplied as an argument when the method is for a listener and the view(Button,Spinner,Switch,etc.) is used to distinguish which view on the layout has been clicked/selected.