Reputation: 765
I'm a newbie with android development, but not really with Java.
What I don't understand is why a method I define in the Button must to take View
as a paremeter.
For example..
in XML
<Button
android:id="@+id/button1"
//etc..
//etc..
android:onClick="displayText" />
As can be seen, this is the onClick method.
When I'm writing Java code the method displayText
will be defined like so
public void displayText(View view){
TextView myTextView = (TextView)findViewById(R.id.textView1);
myTextView.setVisibility(View.VISIBLE);
}
When everything works fine, the text I have originally hidden, will be displayed via a simple click of a button.
When I remove the parameters View view
from this method, the app crashes when I try to click the button.
I fail to understand why.
I'm not necessarily doing anything with the view
in the parameter.
In non android development I could use the view
that is in the parameter and do things with it.. but I don't see that I'm doing anything WITH this parameter.. so why is it required in this method?
Upvotes: 0
Views: 90
Reputation: 765
I have searched Stackoverflow but never found a question that suited what I was looking for so I made this question.
The two answers given here we're a little too short for me to wrap my head around a method having parameters but never using them.
Then I looked at the "Related" section on the side and found a question better worded than mine and answers that were longer and satisfied my question and answered it in more detail.
Thank's to all those that responded here. If anyone else finds them selves in the same problem, here is the question/answer that helped me understand it.
Why do android methods accept View objects, but the objects are unused?
Upvotes: 0
Reputation: 3248
Potentially, the same method could be used to handle several views' click event. The View view
parameter would let you know which one is the source of the event. I.e. which button was clicked.
The reason it is required it's because it has to match the interface. When trying to match the function name in the XML to the functions available, it can't be found.
Upvotes: 2
Reputation: 16651
A Button is a subclass of a View. So when methods take a View, it means they can be get a Button as input, but also other subclasses of View.
The View is given in the parameter, so you can modify the View that was clicked.
BTW, I didn't know you could implement click listeners like this. I normally do it like this:
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view){
// handle
}
});
Upvotes: 1