Reputation: 93
I am new to Android and I went through the view.Java file in Android. But the methods inside this file are not clear and I want to know where the code for setting the OnclickListener is? where the onClick method is actually called?
Upvotes: 3
Views: 718
Reputation: 193
/**
* Register a callback to be invoked when this view is clicked. If this view is not
* clickable, it becomes clickable.
*
* @param l The callback that will run
*
* @see #setClickable(boolean)
*/
public void setOnClickListener(@Nullable OnClickListener l) {
if (!isClickable()) {
setClickable(true);
}
getListenerInfo().mOnClickListener = l;
}
@Raghav: "I would also like to know that , when we see the SetOnclickListener method in view.java it accepts View.OnclickListener parameter. But this parameter is never assigned to the class variable. Why is this so?"
To answer that, it is in fact assigned. If you see in the given code snippet from View.java, the instance of implementing class that you pass to setOnClickListener() from your mainActivity.java is received/stored in the OnClickListener 'l' formal parameter as mentioned by the doc comments above the code. That is then assigned to mOnClickListener (also can be seen in the code snippet).
Upvotes: 2
Reputation: 427
First, give the button in your XML layout file an ID. For example I will call it "btn".
Then in your Java file, write this:
Button button=findViewById(R.id.btn);
This will make the system know that when you call "button", you mean the button with ID called "btn" in XML file.
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
//Insert what you want to do when button is clicked
}
});
Tip: when you are typing, Android Studio will show suggestions. So if you type "button." and haven't finished typing setOnClickListener, it will show you a menu, then you can choose setOnClickListener(). It will save you a lot of time.
Also, inside setOnClickListener()
parentheses, type new Vie
and Android Studio will already show you suggestion new View.setOnClickListener
, and all the @Override part is done for you.
Upvotes: 2