Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드(Android)에서 드래그 앤 드롭 구현하는 방법 – 단계별 완전 가이드

안드로이드 드래그 앤 드롭(Drag and Drop)이란?

이 예제는 안드로이드에서 드래그 앤 드롭 기능을 구현하고 사용하는 방법을 보여줍니다. 안드로이드가 기본 제공하는 드래그 앤 드롭 프레임워크를 활용하면, 사용자가 화면 위의 뷰(View)를 손가락으로 길게 눌러 다른 위치로 옮기는 직관적인 인터랙션을 손쉽게 만들 수 있습니다.

이번 튜토리얼에서는 화면 왼쪽 영역에 있는 이미지 뷰(ImageView)를 오른쪽 영역으로 끌어다 놓는 간단한 예제를 단계별로 살펴보겠습니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 뒤 File ⇒ New Project 메뉴로 이동하여 새 프로젝트를 생성하고, 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면은 두 개의 LinearLayout(왼쪽/오른쪽 영역)으로 구성되며, 왼쪽 영역에는 드래그할 대상인 ImageView가 배치됩니다.

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="MainActivity" >
    <LinearLayout
        android:id="@+id/leftView"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:layout_weight="1"
        android:background="@android:color/darker_gray"
        android:gravity="center_vertical"
        android:orientation="vertical" >
    <ImageView
        android:id="@+id/boxView"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:layout_gravity="center_vertical|center_horizontal"
        android:layout_margin="10dp"
        android:background="@drawable/one" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/rightView"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:layout_weight="1"
        android:background="@android:color/darker_gray"
        android:gravity="center_vertical"
        android:orientation="vertical" >
    </LinearLayout>
</LinearLayout>

3단계: MainActivity 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 핵심 동작은 다음과 같습니다.

  • onTouch(): 사용자가 뷰를 터치하면(ACTION_DOWN) DragShadowBuilder를 통해 드래그를 시작하고, 원본 뷰를 잠시 숨깁니다(INVISIBLE).
  • onDrag(): 드롭 이벤트(ACTION_DROP)가 발생하면 해당 뷰를 기존 부모 ViewGroup에서 제거한 뒤, 드롭된 대상 LinearLayout에 추가하고 다시 화면에 표시합니다.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity implements View.OnTouchListener, View.OnDragListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.boxView).setOnTouchListener(this);
        findViewById(R.id.leftView).setOnDragListener(this);
        findViewById(R.id.rightView).setOnDragListener(this);
    }
    @Override
    public boolean onDrag(View view, DragEvent event) {
        if (event.getAction() == DragEvent.ACTION_DROP) {
            view = (View) event.getLocalState();
            if (view.getId() == R.id.leftView || view.getId() == R.id.rightView) {
                ViewGroup source = (ViewGroup) view.getParent();
                source.removeView(view);
                LinearLayout target = (LinearLayout) view;
                target.addView(view);
            }
            view.setVisibility(View.VISIBLE);
        }
        return true;
    }
    @Override
    public boolean onTouch(View view, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
            view.startDrag(null, shadowBuilder, view, 0);
            view.setVisibility(View.INVISIBLE);
            return true;
        }
        return false;
    }
}

4단계: 매니페스트(Manifest) 설정

androidManifest.xml 파일에 아래 코드를 추가합니다. 별도의 권한 없이 기본 액티비티 등록만으로 드래그 앤 드롭 기능을 사용할 수 있습니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 실행 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드(Android)에서 드래그 앤 드롭 구현하는 방법 – 단계별 완전 가이드

화면의 이미지를 길게 누른 상태로 오른쪽 회색 영역까지 끌어다 놓으면, 이미지가 왼쪽에서 오른쪽 영역으로 이동하는 것을 확인할 수 있습니다. 이처럼 startDrag()OnDragListener만 활용하면 파일 정렬, 아이템 재배치, 휴지통으로 삭제하기 등 다양한 UX에 드래그 앤 드롭을 응용할 수 있습니다.