Search code examples
androidonlongclicklistenerandroiddesignsupportandroid-snackbarsnackbar

Snackbar with setOnLongClickListener


I want to be able to show a snackbar when a button is long pressed. I have a FAB that behaves perfectly but this won't work. (Ignore the orderCounter and +100. That is another part of the long press.)

Button plusButton = (Button) findViewById(R.id.btn_plus);
    plusButton.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            orderCounter += 100;  // orderCounter = orderCounter + 100;
            showOrderCounter();

            return true;
        }
        public void onClick(View view) {
            Snackbar.make(view, "+100", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

The app loads and works perfectly expect that this specific snackbar won't show. What am I doing wrong?


Solution

  • Try moving the Snackbar into the onLongClick.

    public boolean onLongClick(View v) {
            orderCounter += 100;  // orderCounter = orderCounter + 100;
            showOrderCounter();
            Snackbar.make(v, "+100", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            return true;
    }