Event Handling in Android (setOnClickListener) - android

I'm new to Java and Android Development in General. I found a sample which uses the following statement.
sButton.setOnClickListener(this);
in the onCreate() method of the Activity which implements View.OnClickListener where sButton is a Button variable. As far as I understand this register the on click event handler
Later in the sample
public void onClick(View v) {
if(v.getId() == R.id.button_s)
{
//some work
}
this happens.
My question is if it uses the 'this' keyword from inside the activity shouldn't it pass an object of class Activity? If that happens then the Button ID would never match.
I know there are other methods to implement the Button click.
I have a bit of experience with C# and Windows Phone. The procedure there was that the methods were called for the respective buttons without any need for registering them.
Also what is the difference between event handlers and listeners?
Any help would be appreciated! Thanks

The OnClickListener (in this case the Activity instance) is used to declare the behaviour of your application when it consumes click event. However, your application's Main (UI) Thread registers all (UI) events and it will dispatch the appropriate View object as a parameter to your onClick(View v) function.
The snippet you provided - sButton.setOnClickListener(this) simply instructs your application to use the implemented OnClickListener inside your Activity implementation to respond to user clicks. It doesn't forward the this instance as the parameter to the onClick() function, Android OS does that.
In conclusion: The View v parameter in your onClick(View v) function will correspond to the View that the user clicked, regardless of the OnClickListener that has been attached to that View
EDIT: This is (perhaps outdated but) Android's source-code for the performClick() method of the View class. As you can see, inside that method it calls the mOnClickListener.onClick(this) if there's a listener attached, and that's how the view that has been clicked is forwarded to the onClick() method of the appropriate onClickListener object.

One is below
Button btn_stop=(Button) findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
}
});
Second is through XML android:onClick="doClick"
below is code for activity
public void doClick(View v)
{
}

When you do this
sButton.setOnClickListener(this);
this is indeed an instance of Activity. But it is declared as
MyActivity extends Activity implements View.OnClickListener
The important part is that it implements the interface that setOnClickListener takes as argument. This is why it works, this is treated as an OnClickListener, regardless of being an Activity or not.
As for the difference between event handlers and listeners, see this question.

Related

View OnClickListner at Application level Android

I am developing an android application where I stuck at some point. The problem is that I want to track the last action performed in app by tracking onClickListner. So is there any way to set OnclickListner for whole application and then track the last event time. Please Suggest me the way to do that. My assumption is to have a class which extends View class and this class should implement onClickListner. Then all of my buttons should set OnClickListner to Object of this class. but my application have more than 100 buttons so it will increase the complexity of the class. one more problem is that all buttons are performing their activity specific operations.doing all operations from one class will increase complexity.
I am looking to capture onclicklistner throughout the app and then log the event time then transfer the event to the activity where onclickListner was implemented.
An idea might be to create your own OnClickListener, say
class LoggingOnClickListener implements OnClickListener {
public void onClick(View view) {
doLog();
}
}
Now you just have to add super.onClick(view) to add logging to the Button clicks
button.setOnClickListener(new LoggingOnClickListener() {
public void onClick(Button button) {
//handle the click
super.onClick(button);
}
}
The code might very well be flawed as I do not have my IDE open, but should just show the general idea.

android: xml attribute android:onClick, why the method needs View parameter

When I create an android:onClick attribute in the activity's xml, the method defined by onClick needs to have the View parameter, why View?
i.e.
onClick method in my activity----------> public void sayHello(View v){...}
consider the next code, I'm not using the view variable, but I still need to pass it in method, how come?:
public void onClick(View view){
TextView t= new TextView(this);
t=(TextView)this.findViewById(R.id.textView2);
t.setText("new text");
}
So you know which View is calling the method.
It's like implementing the OnClickListener for you activity, the method created is onClick(View v) (or arg0 depending on your Eclipse), defining it from xml is just specifying a sort of listener for the View, and the method from the listener as that argument.
Once you're in the method, you can do a switch for the id of the button, to perform different actions:
public void myOnClickMethod(View v){
switch(v.getId()){
case R.id.button1:
//Do something for button 1
break;
case R.id.button2:
//Do something for button 2
break;
}
}
In short. Android just implements the OnClickListener for you when you define the android:onClick="myOnClickMethod" attribute.
Before answering the question I would like to mention what a view is...
Android app contains activities which are like screens which further contains GUI elements(such as buttons). In simple words, those GUI elements are called views.
Answer for your question...
Just imagine a situation in which your activity has more than one button (Let's consider it to be 5) and on getting clicked those buttons make a call to the same function (namely onClick()).So, how would the program know which button was clicked. The answer is simple just pass a view parameter to the onClick() function which will allow access to the information regarding the button that was clicked.

Query about setOnClickListener() and onClick() of android

what is actually done by setOnClickListener() method and onClick() method during click
events.why this two method is needed during click events.
please explain in details.
onClickListener() method lets you to handle "on click events". You can have statements below this method that will be happening when one of your objects is clicked.
You can visit here to gain more knowledge about these methods.
onClickListener is an interface that allows you to use the onClick method. Here is a link that will describe it in more detail. Basically though, you use the setOnClickListener to implement the method you create.
Here is the link:
http://developer.android.com/guide/topics/ui/ui-events.html
If you use the onClick() function defined in your XML, you have to put the onClick() method in the current Activity. For example:
Main.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onclick:doSomething() />
</LinearLayout>
Main.java
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void doSomething(){
//do something here
}
}
Above will only search for doSomething in Main.Java
This is important if you are using fragments, since the programmatic way of setting onclick listeners (using setOnClickListener()) will probably have the method handling clicks in a fragment's onCreateView() where it will not be found if referred to, from XML.
#pronay biswas When you want explanation for such things just take the cursor of mouse over that text and a pop dialog will appear that will tell you about that particular thing in android if you are using eclipse
what setOnClickListener does
void android.view.View.setOnClickListener(OnClickListener l)
public void setOnClickListener (View.OnClickListener l)
Since: API Level 1
Register a callback to be invoked when this view is clicked. If this view is not
clickable, it becomes clickable.
Parameters
The callback that will run
android.view.View.OnClickListener
// working of View.OnClickListener
public static interface
View.OnClickListener
android.view.View.OnClickListener
Known Indirect Subclasses
CharacterPickerDialog, KeyboardView, QuickContactBadge
CharacterPickerDialog Dialog for choosing accented characters related to a base character.
KeyboardView A view that renders a virtual Keyboard.
QuickContactBadge Widget used to show an image with the standard QuickContact badge and on-click behavior.
Class Overview
Interface definition for a callback to be invoked when a view is clicked.
// OnClickListener
#Override
Specified by: onClick(...) in OnClickListener
public abstract void onClick (View v)
Since: API Level 1
Called when a view has been clicked.
Parameters
v The view that was clicked.

Which is better in implementing click listener?

Which is a good practice in implementing click listener and why? Or is there a better way other than the two? Thanks.
First :
sampleButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
// do something
}
});
Second : implement OnClickListener then override onClick method?
The third option is to set the listener directly in your XML layout:
android:onClick="myClickHandler"
and then implement it in your Activity:
public void myClickHandler(View v){
// do something
}
You're technically doing the 2nd thing with the 1st one. The 1st case uses whats called an anonymous class which implements OnClickListener, but since is anonymous, doesn't have a class name and isn't editable from external classes. Explicitably implementing OnClickListener is useful if you expect to use the same onClick functionality in multiple different locations, or if the click code is long
The first approach is used when you want to perform the action only for a particular case, if many click events require the same action then use the second one.

Is it possible to chain event listeners in Android?

I have an activity which contains QuickContactBadges. I'm looking for a way to either chain event listeners on the QuickContactBadge, or to call the default listener from within an override.
Specifically, what I am looking to do is have the QuickContactBadge, when clicked to show the QuickContact card, and then to setResult and finish, to close my activity.
So either I want to add a second listener to the badge in addition to the default one, or implement something like the following:
bdg.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
QuickContactBadge bdg = (QuickContactBadge) view;
bdg.base.onClick(); // PSEUDO-CODE LINE
setResult(RESULT_CANCELED, null);
finish();
}
});
Are either of these methods possible, or is there some other way I should be doing this?
Well, the answer to what I was trying to do was not actually in an event listener at all.
The key to getting my activity to close when the QuickBadge is clicked was to add android:noHistory="true" to the activity definition in the application manifest file.
Though, it would still be interesting to know yes/no if there is a way to chain event listeners.

Categories

Resources