0

I have a button and when I hold the button for 2 seconds, I want to show an AlertDialog.

This is what I have tried:

btn.setOnTouchListener(new OnSwipeTouchListener(getContext()) {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
            Helper.setTimeout(() -> {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                    builder.setTitle("Message");
                    builder.setMessage(text);
                    builder.show();
                    System.out.println("I am text");
                }
            }, 2000);
        return super.onTouch(view, motionEvent);
    }
}

My method setTimeout():

public static void setTimeout(Runnable runnable, int delay){
    new Handler(Looper.getMainLooper()).postDelayed(runnable, delay);
}

My problem is that sometimes the AlertDialog shows up multiple times and I always get this warning:

W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.

What am I doing wrong?

I don't know if there is a better solution. I have also tried It with

btn.setOnLongClickListener(v -> {
    System.out.println("hold");
    return true;
});

but that doesn't output anything.

hata
  • 11,633
  • 6
  • 46
  • 69
xRay
  • 543
  • 1
  • 5
  • 29
  • 2
    If you just want a long click, not necessarily exactly 2 seconds, just use `setOnLongClickListener`. If you want to implement with touch, refer to [this post](https://stackoverflow.com/questions/7919865/detecting-a-long-press-with-android) – Ricky Mo Nov 09 '21 at 01:22
  • @RickyMo thank you, that post helped me. – xRay Nov 09 '21 at 17:33

1 Answers1

0

You can try this

public class MainActivity extends AppCompatActivity {

Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = findViewById(R.id.button);

    button.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("Message");
                    builder.setMessage("hello");
                    builder.show();
                }
            }, 2000);


            return false;
        }
    });
}
}
Tanveer Hasan
  • 247
  • 2
  • 9