How to implement long press event listener in Android?

In Android, you can listen for long press events by using the OnLongClickListener interface. The specific steps are as follows:

  1. Add a View in the layout file that needs to listen for a long press event, such as a Button.
<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Long Click Me"/>
  1. Find the View in Activity or Fragment and set a long press listener.
Button button = findViewById(R.id.button);
button.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        // 处理长按事件
        return true; // 返回true表示已处理事件,不会触发普通点击事件
    }
});

Write the logic for the long press event in the onLongClick method. Returning true indicates that the event has been handled and will not trigger the regular click event, while returning false will continue to trigger the regular click event.

bannerAds