본문 바로가기
안드로이드 자바

[Android][JAVA]setOnLongClickListener로 롱클릭 이벤트 발생시키기

by teamnova 2023. 6. 8.

안녕하세요. 뷰의 이벤트 리스너 중 setOnLongClickListener를 활용해 예제를 작성해 봤습니다.

먼저 xml 파일입니다.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        android:text="롱클릭"
        android:id="@+id/long_click"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>


</androidx.constraintlayout.widget.ConstraintLayout>

다음은 MainActivity.java 클래스입니다.

public class MainActivity extends AppCompatActivity {
    Button long_click_btn;
    Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
       long_click_btn = findViewById(R.id.long_click);
       long_click_btn.setOnLongClickListener(new View.OnLongClickListener() {
           @Override
           public boolean onLongClick(View view) {
               Toast.makeText(context,"롱클릭 하셨습니다.",Toast.LENGTH_SHORT).show();
               return true;
           }
       });
    }

}

setOnLongClickListener는 버튼 뿐만 아니라 뷰 아이템에게 있는 리스너입니다.

롱클릭을 하게 되면 토스트로 메시지를 띄워보겠습니다.