OnTouch/OnClick listeners. Use both? - android

I have a short question. Should I use in same time OnTouch and OnClick listeners ?
If I`m correct one is for touch screens and other is for devices with out it. Am I wrong ? If not should I use both listeners to secure both kind of devices ?

You only need OnTouch if you have some event that should only happen with a touch screen. If you just want to do something when the user taps (or clicks), then you only need OnClick.

I use both. I've create a class extending from Button class. I've put my custom appearance and interaction (programmaticaly) on the onTouch() method and the functionality for the onClick().

Related

difference between android:onClick and onClickListener [duplicate]

I realize that a similarly-worded question has been asked before, but this is different. I am pretty new at developing android apps and I have three questions regarding the difference(s) between the android:onclick="" XML attribute and the setOnClickListener method.
What are the differences between the two? Is the difference between the two implementations found at compile time or run time or both?
What use cases are favorable to which implementation?
What difference(s) does the use of fragments in Android make in implementation choice?
Difference Between OnClickListener vs OnClick:
OnClickListener is the interface you need to implement and can be set
to a view in java code.
OnClickListener is what waits for someone
to actually click, onclick determines what happens when someone
clicks.
Lately android added a xml attribute to views called android:onclick,
that can be used to handle clicks directly in the view's activity
without need to implement any interface.
You could easily swap one listener implementation with another if you need to.
An OnClickListener enable you to separate the action/behavior of the click event from the View that triggers the event. While for simple cases this is not such a big deal, for complex event handling, this could mean better readability and maintainability of the code
Since OnClickListener is an interface, the class that implements it has flexibilities in determining the instance variables and methods that it needs in order to handle the event. Again, this is not a big deal in simple cases, but for complex cases, we don't want to necessary mix up the variables/methods that related to event handling with the code of the View that triggers the event.
The onClick with function binding in XML Layout is a binding between onClick and the function that it will call. The function have to have one argument (the View) in order for onClick to function.
Both function the same way, just that one gets set through java code and the other through xml code.
setOnClickListener Code Implementation:
Button btn = (Button) findViewById(R.id.mybutton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myFancyMethod(v);
}
});
// some more code
public void myFancyMethod(View v) {
// does something very interesting
}
XML Implementation:
<?xml version="1.0" encoding="utf-8"?>
<!-- layout elements -->
<Button android:id="#+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="myFancyMethod" />
<!-- even more layout elements -->
Performance:
Both are the same in performance. Xml is pre-parsed into binary code while compiling. so there is no over-head in Xml.
Limitation:
android:onClick is for API level 4 onwards, so if you're targeting < 1.6, then you can't use it.
I'm shocked nobody talked about this but be careful, although android:onClick XML seems to be a convenient way to handle click, the setOnClickListener implementation do something additional than adding the onClickListener. Indeed, it put the view property clickable to true.
While it's might not be a problem on most Android implementations, according to the phone constructor, button is always default to clickable = true but other constructors on some phone model might have a default clickable = false on non Button views.
So setting the XML is not enough, you have to think all the time to add android:clickable="true" on non button, and if you have a device where the default is clickable = true and you forget even once to put this XML attribute, you won't notice the problem at runtime but will get the feedback on the market when it will be in the hands of your customers !
In addition, we can never be sure about how proguard will obfuscate and rename XML attributes and class method, so not 100% safe that they will never have a bug one day.
So if you never want to have trouble and never think about it, it's better to use setOnClickListener or libraries like ButterKnife with annotation #OnClick(R.id.button)
Simply:
If you have android:onClick = "someMethod" in xml, it looks for the public void someMethod in your Activity class. OnClickListener is called right from your Activity and it is linked to some particular View. For example someButton.setOnClickListener and in the code below is said what has to be done when someButton is pressed.
Hope it helps :)
As said before: they both are a way to add logic in response to an event, in this case a 'click' event.
I would go for a separation between logic and presentation, just like we do in the HTML/JavaScript world: Leave the XML for presentation and add event listeners by means of code.
There are a couple of reasons why you might want to programmatically set an OnClickListener. The first is if you ever want to change the behaviour of your button while your app is running. You can point your button at another method entirely, or just disable the button by setting an OnClickListener that doesn't do anything.
When you define a listener using the onClick attribute, the view looks for a method with that name only in its host activity. Programmatically setting an OnClickListener allows you to control a button's behaviour from somewhere other than its host activity. This will become very relevant when we use Fragments, which are basically mini activities, allowing you to build reusable collections of views with their own lifecycle, which can then be assembled into activities. Fragments always need to use OnClickListeners to control their buttons, since they're not Activities, and won't be searched for listeners defined in onClick.
If you have several buttons using only one method, I suggest doing it in java. But if you have a button with one specific method, onClick in XML would be better.
It's more convenient to always use android:onClick attribute unless you have a good reason not to, for example, if you instantiate the Button at runtime or you need to declare the click behavior in a Fragment subclass.
I think main difference between them is:
OnClick: When you click on the button with your finger.
OnClickListner: It is may be a wider choice that be implemented in various codes.
For example when you type url "ymail.com", yahoo finds your username and your password from your browser and enable click state button to open your mail. This action should be implemented only in onClickListener.
This is my idea!

Listen all buttons events Android

Its possible to have a listener to all buttons without setting the onClickListener in each button across all activities? and without making a extends button with the listener already set.
No. Each view has to be told what to listen to. You can specify it in xml if you prefer with the onClick attribute, but you'll still need to specify it on each object.
If all the buttons are doing the exact same thing, you can include that in the List kind of a layout and have one button with just one onCLick() event

3 actions 1 button - OnClick Ontouch OnLongClick

Im having a problem with logic as to how to go about this.
I require 1 button to do 3 things.
On click --play a music file once
If held (im guessing OnTouch) the music would play and loop but stop on releasing the thumb.
OnLongClick - goes to a new view for user input.
I have been able to implement 1 and 3.
My problem is if i use the onTouchListner it will eventually fire the OnLongClick Event and I think it will try to run the onClick event when I release the touch .
Ant thoughts would apprecieted
onTouch gives you Motion Event. Thus, you can do a lot of fancy things as it help you separate state of movement. Just to name a few
ACTION_UP
ACTION_DOWN
ACTION_MOVE
Those are common actions we usually implement to get desire result such as dragging view on screen.
On the other hand, onClick doesn't give you much except which view user interacts. onClick is a complete event comprising of focusing,pressing and releasing.
For more information on how to handle single and multitouch events in android visit here
So ,what you need to work this situation with ,is "MyGestureListener".
You can still use what you have implemented Onclick and OnLongClick and instead "OnTouch" I am pretty sure you are meant to use "onDown"/"ON_DOWN".
Here is a list of all the methods you can use: https://developer.android.com/samples/BasicGestureDetect/src/com.example.android.basicgesturedetect/GestureListener.html
Hope it helped.
You better use option 1 normally,then instead of ontouch use onLongClick and write code for a menu to appear with option 2 and 3.
Cheers! :)

Associating onXXX() calls caused by a single user action

Suppose that I have a RadioGroup in Android. When I tap a RadioButton, a number of listeners are called, including the button's OnClickListener.onClick() method and the group's OnCheckedChangeListener.onCheckedChanged() method.
Is there any way to make an association between those events, to know that they were both triggered by the same tap?
Looks like you imported the wrong OnCheckChangeListener.
RadioGroup.OnCheckedChangeListener only includes onCheckedChanged().
Reference: http://developer.android.com/reference/android/widget/RadioGroup.OnCheckedChangeListener.html

Difference between Click and Touch Listeners in Android

I have a bit of doubt. I am using an image button (e.g. Play icon in media player). I want to know which action Listener I am supposed to use, onClickListener or onTouchListener. What is the difference between those two actions and when should I use either.
The answer by #vishy1618 has the key insight of this thread (tried to leave this as a comment there, but too long).
Conceptually, onClick is just a 'wrapper' around a particular sequence of touch events - down, no drag, up. So comparing onTouch vs. onClick is just a low-level API (raw touch events) vs. a high-level API (a logical user 'click').
But, an important compatibility issue: in Android, onClick can also be fired by the KEYBOARD (or trackball, or whatever alternative input/hardware device is being used). But (afaict) there's no support for firing touch events via any other input device apart from the touch screen.
So, if you code your UI against touch events exclusively, you are implicitly requiring a touchscreen. Whereas if you stick to onClick, your app could theoretically work on a non-touch device.
Of course, all 'compliant' Android phones currently do have touch screens ... so this is effectively moot. But if you want your app to work on non-phone hardware, this might be worth considering.
There is some good discussion here:
How to determine if an Android device has a touchscreen?
https://groups.google.com/forum/?fromgroups=#!topic/android-beginners/cjOVcn0sqLg
onClickListener is used whenever a click event for any view is raised, say for example: click event for Button, ImageButton.
onTouchListener is used whenever you want to implement Touch kind of functionality, say for example if you want to get co-ordinates of screen where you touch exactly.
Update:
Just check the official doc for both: onClickListener and onTouchListener.
So from official doc, definition for both are:
onClickListner: Interface definition for a callback to be invoked when a view is clicked.
onTouchListener: Interface definition for a callback to be invoked when a touch event is dispatched to this view. The callback will be invoked before the touch event is given to the view.
The onClickListener is a number of events that are triggered using either the keyboard or the touchscreen. They are performed on a specific view, and the entire view receives the event. In contrast, the onTouchListener is used only for touchscreen events, and they cannot be triggered through the keyboard or any other inputs. They typically also receive the corresponding touch information like the x, y corrdinates, etc.
I think the onClickListener would be appropriate for your application, if you are not using more complex inputs, like gestures, etc.
This question I also got in mind that should use click or touch listener.
Then I have my understandings like this,
When I need any View(Button/Image/etc) to make clickable that means user just don't touch that part of screen but delebrately try to Touch on that part of screen so the next action gets called I use onClickListener , Also another thing is like suppose working with Button we can make it Clickable True/False as per requirement dynamically,Hence in this situations the OnClickListener is preffered.
new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
};
While developing screens where the simple Touch of User is to be taken as action like more in Games or Working with Images that you want to capture that where user has touched and also you need to find the Motion Events up/down/left/right of the Touch I preffer to use onTouchListener.
new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
};
And
In your case I suggest to use the onClickListener
Extra information for anyone viewing this thread in the future:
When you set the FocusableInTouchMode property for the view to "True" onClick will not fire until the second click/touch on the view. I assume the OS treats the first touch as gaining focus only. OnTouch however, fires on the first touch.
When FocusableInTouchMode = "False" both will fire on the first touch.

Categories

Resources