Basic Android : how to handle isPressed action on a button in Android - java

I wrote a working code using isEnabled().
if(btn.isEnabled()){
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// say send a udp packet
}
}
);
}
Now instead of the packet to be sent when the button is clicked, I want to send it when it stays pressed. How do I handle this?
when i tried isPressed instead of isEnabled, there was a blank screen and the activity was not even displayed...
EDIT : also tried btn.isPressed() - it doesn't work ... the udp packet gets sent immediately after I click on the button... I want it to send ONLY when I am pressing it ...
Any help would be appreciated.
Thanks

your condition is vague. "ONLY when I am pressing it" would mean you'll start sending when the button starts being pressed, which would mean on MotionEvent.ACTION_DOWN. if you want some delay before the action gets executed, create a timer thread that would start when MotionEvent.ACTION_DOWN is detected, and will execute your action after a few seconds. the timer should also reset when MotionEvent.ACTION_UP is detected, or if the action is already in progress, interrupt the action.
but honestly, you may want to rephrase your condition.

Not sure if this will work, but worth a try
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.isPressed()){
//do sth.
}
else{
//do sth. else
}
}

Your going to want to use the onTouchListener instead of onClick and stuff. Small change you also want to track when the user lets go.
EDIT adding timer stuff
Timer timer;
UDP request;
btn.setOnTouchListener(new OnTouchListener(){
public boolean onTouch(View v, MotionEvent event){
if(event.getAction() == MotionEvent.ACTION_DOWN){
//TODO start sending udp in background
timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
request.start();
}
},DELAY_MS);
}
if(event.getAction() == MotionEvent.ACTION_UP){
//TODO stop sending udp
timer.cancel()
if(request.isTransmitting()){
request.stop();
}
}
//needed to get both calls
return true;
}
});

Related

How do I do a continuous job when I press and hold until it's released then it stops?

I have a button that when clicked it will increase my mediaplayer for 10s but I want to press and hold it will increase continuously until released.
btn10s.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.seekTo(mp.getCurrentPosition() + 10000);
}
});
Thank !
The method onClick works when you touch and release the button.
But when you want to do something in an event of touching the button,
you need the method called
onTouch (View v, MotionEvent event){}

How to properly set custom long click listener?

I'm trying to set my own long click listener on Unlock button. Whenever I press the Unlock button it summarize duration and I can unlock permanently clicking.
Unlock.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(final View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Unlock.setText("Press to unlock");
isLongPress = true;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (isLongPress) {
Unlock();
}
}
}, longClickDuration); //amount of time of long click
} else if (event.getAction() == MotionEvent.ACTION_UP) {
Unlock.setText("Unlock");
isLongPress = false;
}
return true;
}
});
}catch (Exception e) {
// TODO: handle exception
}
}
If you want to just handle long clicks consider using the following code:
Unlock.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
your code
}
});
But if the Unlock(); should be invoked after a certain (customizable) amount of time, you should measure this time in MotionEvent.ACTION_UP handler. As #Attaullah Khan said, use SystemClock.elapsedRealtime() system timer to correctly count number of milliseconds at two moments (when button was pressed and released) and if the time is greater than longClickDuration then invoke Unlock
The handler.postDelayed that you call in MotionEvent.ACTION_DOWN handler just invokes a check of pressed state after longClickDuration interval and if your button gets suddenly pressed at that moment, the verification passes that is not correct

Hold button down save processing android

I need to fire an event when a user holds down a button, and fire another event, when the user releases it in my app. The events are short Asyc Tasks, which run in background.
The problem is, I know how to make this happen with the OnTouchListener(), but it seems like when you hold down the button, it runs an infinite loop on the onTouch() method, stopping when the user releases it. Although since my Tasks are launched only once, It runs over and over empty, doing nothing.
I'm not sure if there is any other way possible to achieve this, which fires my back events and stops with the loop. It would be beneficial, as a lot of resources in the form of side threads are already being consumed, and I would like to save some useless running of a method. Here is my implementation, if something is wrong with it:
private OnTouchListener down = new OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
// TODO Auto-generated method stub
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
//Async Task
} else if (action == MotionEvent.ACTION_UP) {
//Async Task
}
return false;
}
};

How to check if Button is still clicked after second

I am looking for a way to call a function when a button is pressed and held for one second. When the button is released another function should be called.
I was thinking about an onLongClickedListener but this won't work well for me since the text that is going to be displayed would stay too long or short.
I am thinking a TouchListener could help me because the Action_Up event would give me the option to let the text dissapear when the button isn't pressed anymore. The Action_down event gives me when the button is pressed and I thought I could start a timer when the button is pressed, wait a second, check again if the button still is pressed and then call the function (show the text).
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (v.getId()) {
// the button. I set bFertig.setOnTouchListener(this); in onCreate
case R.id.bFertig:
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// everything works up to here
waitTimerNotif = new CountDownTimer(1000, 500) {
#Override
public void onTick(long arg0) {}
#Override
public void onFinish() {
// TODO Auto-generated method stub
// here im checking if the button still is pressed
if (bFertig.isPressed()) {
// It never goes into here
ShowNotifBox("Fertig", "fertig", false, false,false);
}
}
}.start();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
DissapearNotifBox();
Log.d("Debug", "Button released");
}
break;
}
return true;
}
For the Button in xml:
<Button
android:id="#+id/bFertig"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/fertigbutton"
android:gravity="center"
android:textColor="#ffffff"
android:textSize="18.5dp"
android:clickable="true"/> <!--Googleing suggested I need this for isPressed() to work but it didnt help
Any ideas what I did wrong or why this isnt working? Thanks!
You're returning true, which tells the system that you are handling the touch events, which means the button is not, which means it's probably not updating its pressed state. Try returning false.
Why not use the setOnLongClickListener function?
This should solve your issue.
An example can be find here: setOnLongClickListener

Close activity when clicking anywhere

I want my activity (a normal activity with a digital clock at the center of it) to close when I tap it anywhere. Is there a sort of Activity.setOnClickListener or a way to do it?
Yes on an Activity you override the existing handlers, on controls you add touch listeners, and [activityinstance].finish() gracefully closes your app.
#Override
public boolean onTouchEvent(MotionEvent event) {
this.finish();
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// Write Code Goes Here means >> this.finish();
return false;
}
This will help you.
use onUserInteraction() for finishing your activity this method called Called whenever a key, touch, or trackball event is dispatched to the activity. as doc says

Categories

Resources