btn_Login.setOnClickListener(this);
In android studio.
I've seen this in countless places. What does this mean? I know how this
operates but what is the listener called then?
This example is from: Link
btn_Login.setOnClickListener(this);
In android studio.
I've seen this in countless places. What does this mean? I know how this
operates but what is the listener called then?
This example is from: Link
Suppose that you have 16 Buttons and every button has setOnclicklistener
this means that you are creating many repetitions of similar code to this in your class. And that makes your code ugly, also this is not the efficient way to write your code. So to make your code efficient you have to implement OnClickListener()
on your activity and then for each button use buttonX.setOnClickListener(this)
. Now use the override onClick
method. In this method, you can use either the switch case block or if-else to identify which button is pressed. So in the onClick
method you just have to give ids of the button.
Implement OnClickListener
in Activity
public class MyActivity extends Activity implements View.OnClickListener {
}
For each button use this:
buttonX.setOnClickListener(this);
After this implement override the onClick
method
@Override
public void onClick(View view) {
switch(view.getId){
case R.id.buttonX:
// Do something
break;
}
in that example its defined like this private Button btn_Login;
Button is a class onClickListener is a listener, to set the listener he is using setOnClickListener method.
From the next time if u need to those kind of clarifications don't post in a separate thread, add a comment in that question itself.
Thank You @august alsina
When your class implement View.OnClickListener, you can defined your click of each button in method public void onClick(View v)
. Keyword this
refer to the method onclick. It is good to use this way when there are a lot of button in your class file. You can define following code On Create method:
button1.setOnClickListener(this);
button2.setOnClickListener(this);
and define its definition oncreate method. For example:
public void onClick(View v){
int id= v.getId();
switch (id){
case R.id.btn1: {
//do sth
//break;
}
case R.id.btn2: {
//do sth
//break;
}
...
}
}
In layman's terms
By writing btn_Login.setOnClickListener(this);
whenever btn_login will be pressed program will go to onclick method public void onClick(View v)
and then you can write in the method what you want to do when button is pressed
implements
something interesting.