5

I have seen several articles such as this one describing how to handle a long press event with a button. I can follow these directions but I am wondering if it is possible to do it the same way I handled a click. The way I handled a click was to define the handler in XML as such:

<Button
    android:id="@+id/btn_NextLift"
    ...
    android:onClick="btn_NextLiftClick" />

then in code as such:

public void btn_NextLiftClick(View vw_Current) 
    {...}

I do see the boolean property longClickable in the xml but I don't see where to define an event handler so...???

TIA JB

Community
  • 1
  • 1
GPGVM
  • 5,515
  • 10
  • 56
  • 97

1 Answers1

19

You can't do this via XML. Instead, use:

Button button = (Button) findViewById(R.id.btn_NextLift);

button.setOnLongClickListener(new OnLongClickListener() { 
        @Override
        public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
            return true;
        }
    });

Make sure this code comes after setContentView() has been called.

Also, make sure that the longClickable property is set to true.

Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
  • This is frustrating. I definitely set the code after setContentView but my button still comes up null so I get NullRef exception. – GPGVM Nov 14 '12 at 17:37
  • If I add the LongClick handler to the XML defined click handler then it works. It is as if my button is hiding and can't be found till it raises an event??? – GPGVM Nov 14 '12 at 17:43
  • I was pulled off to another project and now I remember. The buttons are on a relative layout and that is the layout used by the list view for each item. – GPGVM Nov 14 '12 at 18:09
  • I started a new question here: http://stackoverflow.com/questions/13385435/lstview-findviewbyid-returning-null – GPGVM Nov 14 '12 at 18:58