Android — drag'n drop в Андроид


Содержание

Функция Drag / Drop в студии Andro >

Я новичок в программировании для Android. Функция drag and drop в студии Android не работает. Я не могу ничего перетащить на свой телефон. Сейчас мой фрагмент – это вид карты google, и я хочу добавить панель поиска в представление. Это просто не тянет. Когда я пытаюсь добавить его в текст, он говорит, что элемент элемента не разрешен здесь?

Это мой файл activity_maps.xml

Новая версия Android-студии использует 2 xml-файла для каждого макета. Один (например, content_main.xml), встроенный в другой (Activity_main.xml). Вы должны открыть содержимое _ *. Xml и создать в нем дизайн. Надеюсь, поможет.

Функция перетаскивания не работает в Android Studio …. Я также потратил много времени на поиск … какая проблема была в том, чтобы выбрать тему для Activity.

Изображение, приведенное ниже, прояснит ситуацию.

В дополнение к ответу Хамеда мне также пришлось:

File > Invalidate Caches / Restart .

Мне не хватает vim.

После обновления до последней версии Android Studio (2.2) у меня возникла такая проблема.

После некоторых поисков и игр вокруг я обнаружил, что удерживание alt позволяет мне перетаскивать. У меня была опция «удерживать ALT для перетаскивания» в разделе «Настройки-> Внешний вид и поведение»> «Внешний вид».

Либо я уже выбрал этот вариант, и исправление в Android Studio 2.2 сделало его таким, чтобы опция была применена к перетаскиванию с панелью палитр. Или этот параметр был недавно добавлен и по умолчанию установлен на флажок, или при обновлении возникла проблема, когда установлено значение true.

У меня есть эта опция, установленная в IntelliJ, и раньше обычно использовала палитру для студии Android, и я в основном уверен, что я ее использовал, не задерживая перед собой, поэтому я собираюсь с вариантом A (и мне потребовалось неловкое количество времени, пока я Попытался удержать alt).

Я также столкнулся с той же проблемой. Виновником было то, что в моем родительском тесте android.support.wearable.view.BoxInsetLayout я перетаскивал компоненты напрямую, но когда я ставил
FrameLayout внутри тега android.support.wearable.view.BoxInsetLayout, а затем перетащить мои компоненты в FrameLayout, это сработало.

Надеюсь, это поможет кому-то.

Выяснил это, я понял это. Несмотря на то, что панель дизайна видна, а также Палитра и дерево компонентов, я также должен иметь приложение / src / main / res / layout / fragment_main.xml, выбранное на панели «Проект», чтобы фактический дизайн макета был включен.

Я тоже столкнулся с этой проблемой, и я просто исправил это, изменив тему на DeviceDefault.Light для активности.

Drag ‘n’ Drop может работать неправильно, когда у вас есть LinearLayout, в этом состоянии элементы, которые вы перетаскиваете, будут пытаться установить определенным образом (по горизонтали или по вертикали), вместо этого попробуйте изменить основной макет на Relative Layout

Линейная компоновка -> Относительная компоновка

Я знаю, что это старая проблема, ни одна из них не работает для меня, и так получилось, что это была не андроид-студия, которая давала эту проблему, это были окна. Я заметил, что я не мог перетащить что-либо, чтобы щелкнуть и удерживать любой файл на рабочем столе, и нажатие клавиши escape – это то, что исправлено для меня.

Я также был замешан в функции drag & drop. Пока я не понял:

После начала перетаскивания вам нужно отпустить кнопку мыши, и все будет хорошо.

Drag n drop textview в android

9 Hunt [2010-12-11 21:31:00]

Я хочу перетащить текстовое представление n на изображение в android 2.X

пожалуйста, посмотрите на этот снимок ниже.

Здесь «Синий» цвет представляет собой ViewGrop, «Белый» — это ImageView, и изображение устанавливается на ImageView. текст, написанный «Мода», — это TextView. Именно так я реализую структуру. Теперь я хочу разрешить пользователю выбирать TextView и перетаскивать его на любую часть изображения, а затем бросать его по изображению в нужное положение.

На данный момент для ссылки я попытался ссылаться на следующий URL-адрес, но всякий раз, когда я использую TextView вместо Button, ситуация становится ненормальной.

Может ли кто-нибудь дать мне дорожную карту или пример, чтобы сделать это?

1 ответ

8 Решение Snailer [2010-12-12 02:07:00]

Вместо этого попробуйте получить ваш ImageView в качестве холста для рисования.

ImageView CanvasView = (ImageView) findViewById(R.id.fashion_pic)

Здесь вы можете создать свой собственный Bitmap и повторно рисовать его после TouchEvent. Следующий фрагмент содержит необходимый обход для ошибки в 2.1 (или 2.2, я не помню):

Здесь вы создали холст, который уже имеет ваше изображение в качестве фона и рисует текст с переменной x и y. Теперь просто установите OnTouchListener:

Как вы можете видеть, слушатель автоматически обновляет ваше изображение, когда он коснулся, и текст будет следовать за пальцем пользователя. Поскольку вы используете растровое изображение в качестве холста, вы также можете добавить поддержку для сохранения/загрузки изображения, если ваше приложение хочет иметь такую ​​функциональность.

Изменить: Это может быть более удобно, если вы перемещаете строки 1-3 из redrawImage() и размещаете их в другом месте, устанавливая эти объекты в качестве глобальных объектов. Я позволю тебе возиться с этим.

Android — Drag and Drop


Android drag/drop framework allows your users to move data from one View to another View in the current layout using a graphical drag and drop gesture. As of API 11 drag and drop of view onto other views or view groups is supported.The framework includes following three important components to support drag & drop functionality −

Drag event class.

Helper methods and classes.

The Drag/Drop Process

There are basically four steps or states in the drag and drop process −

Started − This event occurs when you start dragging an item in a layout, your application calls startDrag() method to tell the system to start a drag. The arguments inside startDrag() method provide the data to be dragged, metadata for this data, and a callback for drawing the drag shadow.

The system first responds by calling back to your application to get a drag shadow. It then displays the drag shadow on the device.

Next, the system sends a drag event with action type ACTION_DRAG_STARTED to the registered drag event listeners for all the View objects in the current layout.

To continue to receive drag events, including a possible drop event, a drag event listener must return true, If the drag event listener returns false, then it will not receive drag events for the current operation until the system sends a drag event with action type ACTION_DRAG_ENDED.

Continuing − The user continues the drag. System sends ACTION_DRAG_ENTERED action followed by ACTION_DRAG_LOCATION action to the registered drag event listener for the View where dragging point enters. The listener may choose to alter its View object’s appearance in response to the event or can react by highlighting its View.

The drag event listener receives a ACTION_DRAG_EXITED action after the user has moved the drag shadow outside the bounding box of the View.

Dropped − The user releases the dragged item within the bounding box of a View. The system sends the View object’s listener a drag event with action type ACTION_DROP.

Ended − Just after the action type ACTION_DROP, the system sends out a drag event with action type ACTION_DRAG_ENDED to indicate that the drag operation is over.

The DragEvent Class

The DragEvent represents an event that is sent out by the system at various times during a drag and drop operation. This class provides few Constants and important methods which we use during Drag/Drop process.

Constants

Following are all constants integers available as a part of DragEvent class.

Signals the start of a drag and drop operation.

Signals to a View that the drag point has entered the bounding box of the View.

Sent to a View after ACTION_DRAG_ENTERED if the drag shadow is still within the View object’s bounding box.

Signals that the user has moved the drag shadow outside the bounding box of the View.

Signals to a View that the user has released the drag shadow, and the drag point is within the bounding box of the View.

Signals to a View that the drag and drop operation has concluded.

Methods

Following are few important and most frequently used methods available as a part of DragEvent class.

Sr.No. Constants & Description
1

Inspect the action value of this event..

Returns the ClipData object sent to the system as part of the call to startDrag().

Returns the ClipDescription object contained in the ClipData.

Returns an indication of the result of the drag and drop operation.

Gets the X coordinate of the drag point.

Gets the Y coordinate of the drag point.

Returns a string representation of this DragEvent object.

Listening for Drag Event

If you want any of your views within a Layout should respond Drag event then your view either implements View.OnDragListener or setup onDragEvent(DragEvent) callback method. When the system calls the method or listener, it passes to them a DragEvent object explained above. You can have both a listener and a callback method for View object. If this occurs, the system first calls the listener and then defined callback as long as listener returns true.

The combination of the onDragEvent(DragEvent) method and View.OnDragListener is analogous to the combination of the onTouchEvent() and View.OnTouchListener used with touch events in old versions of Android.

Starting a Drag Event


You start with creating a ClipData and ClipData.Item for the data being moved. As part of the ClipData object, supply metadata that is stored in a ClipDescription object within the ClipData. For a drag and drop operation that does not represent data movement, you may want to use null instead of an actual object.

Next either you can extend extend View.DragShadowBuilder to create a drag shadow for dragging the view or simply you can use View.DragShadowBuilder(View) to create a default drag shadow that’s the same size as the View argument passed to it, with the touch point centered in the drag shadow.

Example

Following example shows the functionality of a simple Drag & Drop using View.setOnLongClickListener(), View.setOnTouchListener()and View.OnDragEventListener().

Sr.No. Constants & Description
1
Step Description
1 You will use Android studio IDE to create an Android application and name it as My Application under a package com.example.saira_000.myapplication.
2 Modify src/MainActivity.java file and add the code to define event listeners as well as a call back methods for the logo image used in the example.
3 Copy image abc.png in res/drawable-* folders. You can use images with different resolution in case you want to provide them for different devices.
4 Modify layout XML file res/layout/activity_main.xml to define default view of the logo images.
5 Run the application to launch Android emulator and verify the result of the changes done in the application.

Following is the content of the modified main activity file src/MainActivity.java. This file can include each of the fundamental lifecycle methods.

Following will be the content of res/layout/activity_main.xml file −

In the following code abc indicates the logo of tutorialspoint.com

Following will be the content of res/values/strings.xml to define two new constants −

Following is the default content of AndroidManifest.xml

Let’s try to run your My Application application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project’s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −

Now do long click on the displayed TutorialsPoint logo and you will see that logo image moves a little after 1 seconds long click from its place, its the time when you should start dragging the image. You can drag it around the screen and drop it at a new location.

Android — drag'n drop в Андроид

Android drag/drop framework allows your users to move data from one View to another View in the current layout using a graphical drag and drop gesture.

Although the framework is primarily designed for data movement, you can use it for other UI actions. For example, you could create an app that mixes colors when the user drags a color icon over another icon.

NOTE: You will need to set a minimum SDK version of 11 to use the drag and drop processing.

The Drag & Drop Process

There are basically four steps or states in the drag and drop process −

  • STARTED : This event occurs when you start dragging an item in a layout, your application calls startDrag() method to tell the system to start a drag. The arguments inside startDrag() method provide the data to be dragged, metadata for this data, and a callback for drawing the drag shadow.The system first responds by calling back to your application to get a drag shadow. It then displays the drag shadow on the device.Next, the system sends a drag event with action type ACTION_DRAG_STARTED to the registered drag event listeners for all the View objects in the current layout.To continue to receive drag events, including a possible drop event, a drag event listener must return true, If the drag event listener returns false, then it will not receive drag events for the current operation until the system sends a drag event with action type ACTION_DRAG_ENDED.
  • CONTINUING : The user continues the drag. System sends ACTION_DRAG_ENTERED action followed by ACTION_DRAG_LOCATION action to the registered drag event listener for the View where dragging point enters. The listener may choose to alter its View object’s appearance in response to the event or can react by highlighting its View.The drag event listener receives a ACTION_DRAG_EXITED action after the user has moved the drag shadow outside the bounding box of the View.
  • DROPPED : The user releases the dragged item within the bounding box of a View. The system sends the View object’s listener a drag event with action type ACTION_DROP.
  • ENDED : Just after the action type ACTION_DROP, the system sends out a drag event with action type ACTION_DRAG_ENDED to indicate that the drag operation is over. Here you can display any Toast messages.

Drag Event Listener and Callback Method

The DragEvent represents an event that is sent out by the system at various times during a drag and drop operation. This class provides few Drag Events and important methods which we use during Drag/Drop process.

Following are all events integers available as a part of DragEvent class.

Drag Event Meaning
ACTION_DRAG_STARTED Signals the start of a drag and drop operation.
ACTION_DRAG_ENTERED Signals to a View that the drag point has entered the bounding box of the View.
ACTION_DRAG_LOCATION Sent to a View after ACTION_DRAG_ENTERED if the drag shadow is still within the View object’s bounding box.
ACTION_DRAG_EXITED Signals that the user has moved the drag shadow outside the bounding box of the View.
ACTION_DROP Signals to a View that the user has released the drag shadow, and the drag point is within the bounding box of the View.
ACTION_DRAG_ENDED Signals to a View that the drag and drop operation has concluded.

Example

In this tutorial, we will implement a drag-and-drop operation with TextView, ImageView and Button.

Andro >Last modified on June 26th, 2015 by Joe.

This Android tutorial is to help you learn about how to use drag and drop feature in an Android application. Drag and drop feature is a way of interacting with UI for long with computers. Now in the Mobile and touch screen revolution, drag and drop is becoming an important UI gesture. Lots of games are using drag and drop as a primary way of playing the game. Angry birds is one such popular game which uses drag and drop as its primary game control.

Just a history snippet about drag and drop. In Windows OS 2.0 version, the drag and drop gesture was first introduced in a shareware program (WinTools) by Jeffrey Greenberg.


Drag and Drop Android API

In this tutorial, we shall learn about the Android APIs behind drag and drop, and how to use it by creating a sample Android application. OnTouchListener and OnDragListener are the key interfaces that needs to be implemented for drag and drop. These are callback interfaces and it has methods such as onLongPress and onTouch which will be triggered by Android when user does a drag and drop. Essentially with a drag and drop, we use it to move an Android View from one UI point to another.

Steps for Drag and Drop Implementation

  1. Design Layout: Design and Android layout that contains two or more bounding spaces and the view to be dragged.
  2. Create Activity: Create activity which implements required Android listener interfaces.
  3. Define Callbacks: Define the drag and drop call back functions onTouch() and onDrag().

Step 1. Design Android Layout

  • Need to create two or more bounding spaces.
  • Create Android views to be dragged between available bounding spaces.

The bounding space is nothing but any view like Linear layout, Relative layout, listview or like such views, which will contain the view for drag and drop. When the user touches this view, the drag event will be triggered.

Step 2. Create Android Activity

An Android activity class should be created and let it to implement the required drag and drop listener classes. These interfaces contains the drag and drop call back functions that will be called by the runtime when the event occurs.

Step 3. Define Drag and Drop Callbacks

OnTouchListener and OnDragListener are the two interfaces that needs to be implemented for drag and drop callback. These two Android interfaces contain one method each, respectively onTouch and onDrag . We can even use OnLongClickListener, if so then the respective method to be implemented is onLongClick. For onTouch event, MotionEvent object and the View object should be sent as arguments. For onDrag event the DragEvent object and View object should be passed.

onTouch() Drag and Drop Callback

When the user presses the View to be dragged, the methods onTouch() and onLongClick() will be invoked by the Android runtime. We should have our application logic inside the method and that will executed on drag callback.

How do we pass meta data onDrag?

Clip data should be created and it should have data to be dragged and clip description. This clip data can be accessed on leaving the drag control using getClipData(). This clip data is optional. If the use case requires to pass information, then this can be used. If created, the data will be sent via the startDrag() method. On invoking the startDrag(), the application will intimate the system about the start of the drag.

How do we show drag shadow?

Before calling startDrag a shadowBuilder object should be created. Pass the view instance to View.DragShadowBuilder(view) to show drag shadow.

onDrag() Drag and Drop Callback

After the start of the drag is intimated to Android runtime, immediately it will allow the DragEventListener to handle the drag event using the onDrag() method. It holds two arguments as View and DragEvent object. On handling the drag event there are several possible actions. That action is returned by the method getAction(). Those actions have different states and they are listed as follows.

  • ACTION_DRAG_STARTED – This action will be returned after the startDrag method is invoked.
  • ACTION_DRAG_ENTERED – Whenever the Andro >Download Android Sample Project Code for Drag and Drop

In this example Android application, I will demonstrate the drag and drop gesture by moving a TextView from one LinearLayout to another.

Our Android activity has Two LinearLayout Views which are identified as pinkLayout and yellowLayout. Then a TextView to be created with the pinkLayout.

activity_main.xml

This view will be used to set the listeners OnTouchListener and OnDragListener which will be the Android callback handlers for drag and drop. Set those listeners to the view.

Define, the onTouch(), onDrag(), drag and drop call back methods.

We can use MotionEvent to handle various actions. When the Android system dispatches the event information to the DragListener, then onDrag() method will be invoked. Since there are so many action among entire drag and drop operation, a switch case is created to cover all possible actions. The current action is got by the dragevent.getAction().

On drop, the current view state during the drag is retrieved by the getLocalState() method. The initial view position before drop event, is removed from the parent and positioned into required bounding area which is here the LinearLayout.

The entire onDrag() method can be defined as follows.

To continue with the operation of OnDragEventListener, the onDrag() method should return true after each action. Following is the complete drag and drop Android activity class.

Android Drag and Drop Example App Output


Comments on «Andro >

This is the best ever Android tutorial I have read. You have covered the drag and drop topic completely and so crystal clear. Amazing work.

Please write more on Android.
Thanks,
Meera.

Happy Valentines Day Joe!
Big like for your tutorials especially for design patterns part.
Tanx buddy.

Hi ,As You have very good example for Android ,Please Add Android in Menu item ,so we can find all Android tutorials at once.

Anna Seriously u r great please i have some doubt in JQuery.. if u r means contact my mail id……….

Very good tutorial and it is very helpful to me

hello.
I was unable to run this program on my eclipse. it kept crashing the emulator. Did anyone else get this error as well. Please reply. Very urgent.
Thanks.

Sooperb and plain simple tutorail

I Have the same problem the App crashes on eclipse. Below is the log…
04-27 11:01:45.155: E/AndroidRuntime(523): FATAL EXCEPTION: main
04-27 11:01:45.155: E/AndroidRuntime(523): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo: java.lang.ClassNotFoundException: com.javapapers.android.drag_drop.MainActivity in loader dalvik.system.PathClassLoader [/data/app/com.javapapers.android.drag_drop-1.apk]

I Have the same problem the App crashes on eclipse. Below is the log…
04-27 11:01:45.155: E/AndroidRuntime(523): FATAL EXCEPTION: main
04-27 11:01:45.155: E/AndroidRuntime(523): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo : java.lang.ClassNotFoundException: com.javapapers.android.drag_drop.MainActivity in loader dalvik.system.PathClassLoader [/data/app/com.javapapers.android.drag_drop-1.apk]

hai sir
i Download your code and run that project but it gives force shut down.when i debug that project that shows error called “source not found”

Hey thanks for this awesome tutorial. But with above code when we drop textVeiw, by default it goes into Top-Left corner.. But I want to place it where user has dropped(i.e. anywhere on screen) How can I achieve that? Please help..
Thanks in advance.. :-)

Thank you for such a nice & easy tut :-)

Change your layout ‘Linear’ to ‘Relative’.. That ‘ll do.

Man, these texts of yours are so helpfull… thanks very much.

Your tutorial is the best tutorial so far. Each word is articulated with precision. Thanks.

How to drag from fragment to canvas? Is it possible to have multiple fragments(hide/show) with canvas? How to implement this? I will really appreciate your reply.

nice tutorial, all ur android tutorials are best

I have a query.
I have a layout at center of screen.
I want to drag a whole layout to left,right,up,down anywhere.

Now,
When I move layout to left from center I want to show
one Image on it (dislike).

When I move layout to right from center I want to show
one Image on it (like).

Nice tutorial, but everytime I drag it to another layout it goes to upper left corner. I want to place where I dropped the text.

hi Joe
I want to drag and drop a file from one device to another device.can you plz help me……..

Hi, nice tutorial, but there is another approach yet how to provide drag and drop even on old versions of android. By overriding onLayout and onMeasure on ViewGroup. As a drag item placeholder you can use items window put into the WindowManager.

Nice Help sir. Best drag and drop tutorial in the net.

Amazing work, the best Tut I’ve found!
Just a question, what do I change if I want the TextView to be dragged and dropped just once?

Excellent work man…. Thanks and pls write more similar tutorials.

Change the android:minSdkVersion in AndroidMenifest.xml to “11”. It is not working in “8”

I have following code for dragging and dropping the image view in same layout but it get invisible at ACTION_DROP event will you please tell me where I’m getting wrong..

public class MainActivity extends Activity <
ImageView ima;
private static final String IMAGEVIEW_TAG = “Android Logo”;
String msg;

@Override
public void onCreate(Bundle savedInstanceState) <
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ima = (ImageView)findViewById(R.id.iv_logo);
// Sets the tag
ima.setTag(IMAGEVIEW_TAG);

@SuppressLint(“InlinedApi”)
@Override
public boolean onTouch(View v, MotionEvent event) <
if (event.getAction() == MotionEvent.ACTION_DOWN) <
ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());

String[] mimeTypes = ;
ClipData dragData = new ClipData(v.getTag().toString(), mimeTypes, item);
// Instantiates the drag shadow builder.
DragShadow dragShadow=new DragShadow(v);

// Starts the drag
v.startDrag(dragData // the data to be dragged
, dragShadow // the drag shadow builder
, v // no need to use local data
, 0 // flags (not currently used, set to 0)
);
v.setVisibility(View.INVISIBLE);
return true;
>
else <
return false;
>
>
>);

// Create and set the drag event listener for the View
ima.setOnDragListener( new OnDragListener() <
@Override
public boolean onDrag(View v, DragEvent event) <
switch(event.getAction())
<
case DragEvent.ACTION_DRAG_STARTED:
Log.d(msg, “Action is DragEvent.ACTION_DRAG_STARTED”);
// Do nothing
break;

case DragEvent.ACTION_DRAG_ENTERED:
Log.d(msg, “Action is DragEvent.ACTION_DRAG_ENTERED”);
v.invalidate();
break;


case DragEvent.ACTION_DRAG_EXITED :
Log.d(msg, “Action is DragEvent.ACTION_DRAG_EXITED”);
v.invalidate();
break;

case DragEvent.ACTION_DRAG_LOCATION :
Log.d(msg, “Action is DragEvent.ACTION_DRAG_LOCATION”);
break;

case DragEvent.ACTION_DRAG_ENDED :
Log.d(msg, “Action is DragEvent.ACTION_DRAG_ENDED”);
v.invalidate();
// Do nothing
break;

case DragEvent.ACTION_DROP:
Log.d(msg, “ACTION_DROP event”);

View view=(View) event.getLocalState();
view.setVisibility(View.VISIBLE);
view.invalidate();
return true;
default: break;
>
return true;
>
>);
>

private class DragShadow extends View.DragShadowBuilder
<

public DragShadow(View view) <
super(view);
>

@Override
public void onDrawShadow(Canvas canvas) <
super.onDrawShadow(canvas);
>

@Override
public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) <
View v= getView();

int height=v.getHeight();
int w >

shadowSize.set(width, height);
shadowTouchPoint.set((int)width/2,(int)height/2);
>

First of all I would like to say thanks for providing clear and in depth understanding of the framework. All your android tutorials are great.

I have a query, I want to get the last position to which view is dragged. As per docs getX() and getY() will not return valid value on ACTION_DRAG_ENDED. So, is there anr alternative through which I can get these values?

In simple, You are Awesome Sir .

While doing dragging, is there a way to cancel the drag operations using some external operation or is there a way to abort the dragging, without releasing the view (which is getting dragged)?

Nice Android tutorial. Really helps…

i want a bubble interface which remains on top of all layout and while moving the bubble to any image or word it copies it .the bubble does all for you . IS there any class for that.
Can you please write Android tutorial for this?

Hi , I am developed drag and drop. But, I have to reset back to previous position after dropping. Please tell me.

Sir actually i want to build dragshadow from original resources according to drag and drop of it’s original sizes .but it not happening by me if you have any solution plz mailed me .

You have given such a beautiful Android tutorial.

Comments are closed for «Android Drag and Drop».

Android — Drag and Drop

Android drag/drop framework allows your users to move data from one View to another View in the current layout using a graphical drag and drop gesture. As of API 11 drag and drop of view onto other views or view groups is supported.The framework includes following three important components to support drag & drop functionality −

Drag event class.

Helper methods and classes.

The Drag/Drop Process

There are basically four steps or states in the drag and drop process −

Started − This event occurs when you start dragging an item in a layout, your application calls startDrag() method to tell the system to start a drag. The arguments inside startDrag() method provide the data to be dragged, metadata for this data, and a callback for drawing the drag shadow.

The system first responds by calling back to your application to get a drag shadow. It then displays the drag shadow on the device.

Next, the system sends a drag event with action type ACTION_DRAG_STARTED to the registered drag event listeners for all the View objects in the current layout.

To continue to receive drag events, including a possible drop event, a drag event listener must return true, If the drag event listener returns false, then it will not receive drag events for the current operation until the system sends a drag event with action type ACTION_DRAG_ENDED.

Continuing − The user continues the drag. System sends ACTION_DRAG_ENTERED action followed by ACTION_DRAG_LOCATION action to the registered drag event listener for the View where dragging point enters. The listener may choose to alter its View object’s appearance in response to the event or can react by highlighting its View.

The drag event listener receives a ACTION_DRAG_EXITED action after the user has moved the drag shadow outside the bounding box of the View.

Dropped − The user releases the dragged item within the bounding box of a View. The system sends the View object’s listener a drag event with action type ACTION_DROP.

Ended − Just after the action type ACTION_DROP, the system sends out a drag event with action type ACTION_DRAG_ENDED to indicate that the drag operation is over.

The DragEvent Class

The DragEvent represents an event that is sent out by the system at various times during a drag and drop operation. This class provides few Constants and important methods which we use during Drag/Drop process.

Constants


Following are all constants integers available as a part of DragEvent class.

Signals the start of a drag and drop operation.

Signals to a View that the drag point has entered the bounding box of the View.

Sent to a View after ACTION_DRAG_ENTERED if the drag shadow is still within the View object’s bounding box.

Signals that the user has moved the drag shadow outside the bounding box of the View.

Signals to a View that the user has released the drag shadow, and the drag point is within the bounding box of the View.

Signals to a View that the drag and drop operation has concluded.

Methods

Following are few important and most frequently used methods available as a part of DragEvent class.

Sr.No. Constants & Description
1

Inspect the action value of this event..

Returns the ClipData object sent to the system as part of the call to startDrag().

Returns the ClipDescription object contained in the ClipData.

Returns an indication of the result of the drag and drop operation.

Gets the X coordinate of the drag point.

Gets the Y coordinate of the drag point.

Returns a string representation of this DragEvent object.

Listening for Drag Event

If you want any of your views within a Layout should respond Drag event then your view either implements View.OnDragListener or setup onDragEvent(DragEvent) callback method. When the system calls the method or listener, it passes to them a DragEvent object explained above. You can have both a listener and a callback method for View object. If this occurs, the system first calls the listener and then defined callback as long as listener returns true.

The combination of the onDragEvent(DragEvent) method and View.OnDragListener is analogous to the combination of the onTouchEvent() and View.OnTouchListener used with touch events in old versions of Android.

Starting a Drag Event

You start with creating a ClipData and ClipData.Item for the data being moved. As part of the ClipData object, supply metadata that is stored in a ClipDescription object within the ClipData. For a drag and drop operation that does not represent data movement, you may want to use null instead of an actual object.

Next either you can extend extend View.DragShadowBuilder to create a drag shadow for dragging the view or simply you can use View.DragShadowBuilder(View) to create a default drag shadow that’s the same size as the View argument passed to it, with the touch point centered in the drag shadow.

Example

Following example shows the functionality of a simple Drag & Drop using View.setOnLongClickListener(), View.setOnTouchListener()and View.OnDragEventListener().

Sr.No. Constants & Description
1
Step Description
1 You will use Android studio IDE to create an Android application and name it as My Application under a package com.example.saira_000.myapplication.
2 Modify src/MainActivity.java file and add the code to define event listeners as well as a call back methods for the logo image used in the example.
3 Copy image abc.png in res/drawable-* folders. You can use images with different resolution in case you want to provide them for different devices.
4 Modify layout XML file res/layout/activity_main.xml to define default view of the logo images.
5 Run the application to launch Android emulator and verify the result of the changes done in the application.

Following is the content of the modified main activity file src/MainActivity.java. This file can include each of the fundamental lifecycle methods.

Following will be the content of res/layout/activity_main.xml file −

In the following code abc indicates the logo of tutorialspoint.com

Following will be the content of res/values/strings.xml to define two new constants −

Following is the default content of AndroidManifest.xml

Let’s try to run your My Application application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project’s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −

Now do long click on the displayed TutorialsPoint logo and you will see that logo image moves a little after 1 seconds long click from its place, its the time when you should start dragging the image. You can drag it around the screen and drop it at a new location.

Функция Drag/Drop в студии Android не работает

Я новичок в программировании для Android. Функция drag and drop в студии Android не работает. Я не могу ничего перетащить на свой телефон. Сейчас мой фрагмент — это вид карты google, и я хочу добавить панель поиска в представление. Это просто не тянет. Когда я пытаюсь добавить его в текст, он говорит, что элемент элемента не разрешен здесь?

Это мой файл activity_maps.xml

новая версия Android-студии использует 2 xml файла для каждого макета. Один (например, content_main.xml), встроенный в другой (Activity_main.xml). вы должны открыть содержимое _ *. xml и создать в нем дизайн. надеюсь, что это поможет.


В дополнение к ответу Хамеда мне также пришлось:

File > Invalidate Caches / Restart .

Мне не хватает vim.

Функция перетаскивания не работает в Android Studio. Я также потратил много времени на поиск. какая проблема была связана с выбором темы для Activity.

Ниже приведено изображение.

После обновления до последней версии Android Studio (2.2) у меня появилась эта проблема.

После некоторого поиска и игры, я обнаружил, что нажатие на alt позволяет моему перетаскивать. У меня была опция «удерживать ALT для перетаскивания», отмеченная в Settings-> «Внешний вид и поведение»> «Внешний вид».

Либо я уже выбрал этот параметр, и исправление в Android Studio 2.2 сделало его таким, чтобы параметр применялся для перетаскивания с помощью панели палитры, ИЛИ этот параметр был недавно добавлен и по умолчанию установлен на флажок, или возникла проблема при обновлении, для которого установлено значение true.

Я установил эту опцию в IntelliJ, и раньше я обычно использовал студийную палитру Android, и в основном я уверен, что использовал ее без необходимости удерживать нажатой Alt, поэтому я использую опцию A (и это заняло у меня смущающее количество времени, пока я пытался удерживать Alt).

Как реализовать Drag and Drop в Android?

Я разрабатываю игру-головоломку, где пользователь должен упорядочить изображения в сетке. Скриншот представлен ниже

Я хочу, чтобы перетащить изображение одной ячейки сетки в другую ячейку. Я искал много сайтов и каждый, где я нашел примеры с API перетаскивания (I.e., используя OnDragListener и т. Д.), Который был представлен в Android 3.0, но мое приложение должно работать в Android 2.2.

Поэтому, пожалуйста, помогите мне, как реализовать его с помощью трогательной API (т.е. OnTouchListener и т.д.)

Создан 15 фев. 12 2012-02-15 11:35:39 Chandra Sekhar

1 ответ

Один из способов сделать это было бы взять х & у расположения прикосновения по отношению к сетке.

IE. в сетке 10×10 на площади 100×100.

Если касание было в 25,25, оно выбрало бы квадрат 2,2 (используя массив). Затем вы можете сохранить это местоположение в переменной (чтобы переместить любую фигуру в нее, которую вы меняете), и перетащить обновление растрового изображения x, y по отношению к касанию.

Как только вы поднимите свой палец, скажем, 75,75, он установит кусочек головоломки на 7,7 и переместит эту штуку на 2,2.

Я использовал что-то похожее, меньше перетаскивания, на моей игре Lazer Maze Lite. Шахта была в основном перемещение зеркала и бомбы на ощупь, хотя, но .

Создан 27 мар. 12 2012-03-27 02:48:00 a54studio

Drag and Drop Andro > by ProxyAdmin · Published November 28, 2020 · Updated January 1, 2020

With the Android drag/drop framework, you can allow your users to move data from one View to another View in the current layout using a graphical drag and drop gesture. The framework includes a drag event class, drag listeners, and helper methods and classes.

When you start a drag, you include both the data you are moving and metadata describing this data as part of the call to the system. During the drag, the system sends drag events to the drag event listeners or callback methods of each View in the layout. The listeners or callback methods can use the metadata to decide if they want to accept the data when it is dropped.

Your application tells the system to start a drag by calling the startDrag(ClipData data, DragShadowBuilder shadowBuilder, Object myLocalState, int flags) method. This tells the system to start sending drag events. The method also sends the data that you are dragging.

Drag events

ACTION_DRAG_STARTED – Received just after the application calls startDrag() and gets a drag shadow.
ACTION_DRAG_ENTERED – Received when the drag shadow has just entered the bounding box of the View
ACTION_DRAG_LOCATION – Received while the drag shadow is still within the bounding box of the View.
ACTION_DRAG_EXITED – Received after the user has moved the drag shadow outside the bounding box of the View
ACTION_DROP – Received when the user releases the drag shadow over the View object.
ACTION_DRAG_ENDED – Received when the system is ending the drag operation.

Drag Shadow

During a drag and drop operation, the system displays a image that the user drags. The image is called a drag shadow. You create it with methods you declare for a View.DragShadowBuilder object, and then pass it to the system when you start a drag using startDrag().

ClipData

For case of data movement in drag and drop, we use ClipData to represent it. It is passed in startDrag() and contains description about data being dragged.

Sample Drag and Drop Application

[su_button url=”https://github.com/andro icon=”icon: arrow-circle-o-down”]Download Full Source Code[/su_b[/su_button]p>

In our application, we will create four box views and two parent views for drag and drop operations. As soon as any of box views are touched, we will call startDrag() for that view and on getting drop event on any of the left or right parent view, we will detach it from source parent view and add it to target parent view. Lets start creating application step by step.

Andro >Last modified on June 26th, 2015 by Joe.

This Android tutorial is to help you learn about how to use drag and drop feature in an Android application. Drag and drop feature is a way of interacting with UI for long with computers. Now in the Mobile and touch screen revolution, drag and drop is becoming an important UI gesture. Lots of games are using drag and drop as a primary way of playing the game. Angry birds is one such popular game which uses drag and drop as its primary game control.

Just a history snippet about drag and drop. In Windows OS 2.0 version, the drag and drop gesture was first introduced in a shareware program (WinTools) by Jeffrey Greenberg.

Drag and Drop Android API


In this tutorial, we shall learn about the Android APIs behind drag and drop, and how to use it by creating a sample Android application. OnTouchListener and OnDragListener are the key interfaces that needs to be implemented for drag and drop. These are callback interfaces and it has methods such as onLongPress and onTouch which will be triggered by Android when user does a drag and drop. Essentially with a drag and drop, we use it to move an Android View from one UI point to another.

Steps for Drag and Drop Implementation

  1. Design Layout: Design and Android layout that contains two or more bounding spaces and the view to be dragged.
  2. Create Activity: Create activity which implements required Android listener interfaces.
  3. Define Callbacks: Define the drag and drop call back functions onTouch() and onDrag().

Step 1. Design Android Layout

  • Need to create two or more bounding spaces.
  • Create Android views to be dragged between available bounding spaces.

The bounding space is nothing but any view like Linear layout, Relative layout, listview or like such views, which will contain the view for drag and drop. When the user touches this view, the drag event will be triggered.

Step 2. Create Android Activity

An Android activity class should be created and let it to implement the required drag and drop listener classes. These interfaces contains the drag and drop call back functions that will be called by the runtime when the event occurs.

Step 3. Define Drag and Drop Callbacks

OnTouchListener and OnDragListener are the two interfaces that needs to be implemented for drag and drop callback. These two Android interfaces contain one method each, respectively onTouch and onDrag . We can even use OnLongClickListener, if so then the respective method to be implemented is onLongClick. For onTouch event, MotionEvent object and the View object should be sent as arguments. For onDrag event the DragEvent object and View object should be passed.

onTouch() Drag and Drop Callback

When the user presses the View to be dragged, the methods onTouch() and onLongClick() will be invoked by the Android runtime. We should have our application logic inside the method and that will executed on drag callback.

How do we pass meta data onDrag?

Clip data should be created and it should have data to be dragged and clip description. This clip data can be accessed on leaving the drag control using getClipData(). This clip data is optional. If the use case requires to pass information, then this can be used. If created, the data will be sent via the startDrag() method. On invoking the startDrag(), the application will intimate the system about the start of the drag.

How do we show drag shadow?

Before calling startDrag a shadowBuilder object should be created. Pass the view instance to View.DragShadowBuilder(view) to show drag shadow.

onDrag() Drag and Drop Callback

After the start of the drag is intimated to Android runtime, immediately it will allow the DragEventListener to handle the drag event using the onDrag() method. It holds two arguments as View and DragEvent object. On handling the drag event there are several possible actions. That action is returned by the method getAction(). Those actions have different states and they are listed as follows.

  • ACTION_DRAG_STARTED – This action will be returned after the startDrag method is invoked.
  • ACTION_DRAG_ENTERED – Whenever the Andro >Download Android Sample Project Code for Drag and Drop

In this example Android application, I will demonstrate the drag and drop gesture by moving a TextView from one LinearLayout to another.

Our Android activity has Two LinearLayout Views which are identified as pinkLayout and yellowLayout. Then a TextView to be created with the pinkLayout.

activity_main.xml

This view will be used to set the listeners OnTouchListener and OnDragListener which will be the Android callback handlers for drag and drop. Set those listeners to the view.

Define, the onTouch(), onDrag(), drag and drop call back methods.

We can use MotionEvent to handle various actions. When the Android system dispatches the event information to the DragListener, then onDrag() method will be invoked. Since there are so many action among entire drag and drop operation, a switch case is created to cover all possible actions. The current action is got by the dragevent.getAction().

On drop, the current view state during the drag is retrieved by the getLocalState() method. The initial view position before drop event, is removed from the parent and positioned into required bounding area which is here the LinearLayout.

The entire onDrag() method can be defined as follows.

To continue with the operation of OnDragEventListener, the onDrag() method should return true after each action. Following is the complete drag and drop Android activity class.

Android Drag and Drop Example App Output

Comments on «Andro >


This is the best ever Android tutorial I have read. You have covered the drag and drop topic completely and so crystal clear. Amazing work.

Please write more on Android.
Thanks,
Meera.

Happy Valentines Day Joe!
Big like for your tutorials especially for design patterns part.
Tanx buddy.

Hi ,As You have very good example for Android ,Please Add Android in Menu item ,so we can find all Android tutorials at once.

Anna Seriously u r great please i have some doubt in JQuery.. if u r means contact my mail id……….

Very good tutorial and it is very helpful to me

hello.
I was unable to run this program on my eclipse. it kept crashing the emulator. Did anyone else get this error as well. Please reply. Very urgent.
Thanks.

Sooperb and plain simple tutorail

I Have the same problem the App crashes on eclipse. Below is the log…
04-27 11:01:45.155: E/AndroidRuntime(523): FATAL EXCEPTION: main
04-27 11:01:45.155: E/AndroidRuntime(523): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo: java.lang.ClassNotFoundException: com.javapapers.android.drag_drop.MainActivity in loader dalvik.system.PathClassLoader [/data/app/com.javapapers.android.drag_drop-1.apk]

I Have the same problem the App crashes on eclipse. Below is the log…
04-27 11:01:45.155: E/AndroidRuntime(523): FATAL EXCEPTION: main
04-27 11:01:45.155: E/AndroidRuntime(523): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo : java.lang.ClassNotFoundException: com.javapapers.android.drag_drop.MainActivity in loader dalvik.system.PathClassLoader [/data/app/com.javapapers.android.drag_drop-1.apk]

hai sir
i Download your code and run that project but it gives force shut down.when i debug that project that shows error called “source not found”

Hey thanks for this awesome tutorial. But with above code when we drop textVeiw, by default it goes into Top-Left corner.. But I want to place it where user has dropped(i.e. anywhere on screen) How can I achieve that? Please help..
Thanks in advance.. :-)

Thank you for such a nice & easy tut :-)

Change your layout ‘Linear’ to ‘Relative’.. That ‘ll do.

Man, these texts of yours are so helpfull… thanks very much.

Your tutorial is the best tutorial so far. Each word is articulated with precision. Thanks.

How to drag from fragment to canvas? Is it possible to have multiple fragments(hide/show) with canvas? How to implement this? I will really appreciate your reply.

nice tutorial, all ur android tutorials are best

I have a query.
I have a layout at center of screen.
I want to drag a whole layout to left,right,up,down anywhere.

Now,
When I move layout to left from center I want to show
one Image on it (dislike).

When I move layout to right from center I want to show
one Image on it (like).

Nice tutorial, but everytime I drag it to another layout it goes to upper left corner. I want to place where I dropped the text.

hi Joe
I want to drag and drop a file from one device to another device.can you plz help me……..

Hi, nice tutorial, but there is another approach yet how to provide drag and drop even on old versions of android. By overriding onLayout and onMeasure on ViewGroup. As a drag item placeholder you can use items window put into the WindowManager.

Nice Help sir. Best drag and drop tutorial in the net.

Amazing work, the best Tut I’ve found!
Just a question, what do I change if I want the TextView to be dragged and dropped just once?

Excellent work man…. Thanks and pls write more similar tutorials.

Change the android:minSdkVersion in AndroidMenifest.xml to “11”. It is not working in “8”

I have following code for dragging and dropping the image view in same layout but it get invisible at ACTION_DROP event will you please tell me where I’m getting wrong..

public class MainActivity extends Activity <
ImageView ima;
private static final String IMAGEVIEW_TAG = “Android Logo”;
String msg;

@Override
public void onCreate(Bundle savedInstanceState) <
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ima = (ImageView)findViewById(R.id.iv_logo);
// Sets the tag
ima.setTag(IMAGEVIEW_TAG);

@SuppressLint(“InlinedApi”)
@Override
public boolean onTouch(View v, MotionEvent event) <
if (event.getAction() == MotionEvent.ACTION_DOWN) <
ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());

String[] mimeTypes = ;
ClipData dragData = new ClipData(v.getTag().toString(), mimeTypes, item);
// Instantiates the drag shadow builder.
DragShadow dragShadow=new DragShadow(v);

// Starts the drag
v.startDrag(dragData // the data to be dragged
, dragShadow // the drag shadow builder
, v // no need to use local data
, 0 // flags (not currently used, set to 0)
);
v.setVisibility(View.INVISIBLE);
return true;
>
else <
return false;
>
>
>);

// Create and set the drag event listener for the View
ima.setOnDragListener( new OnDragListener() <
@Override
public boolean onDrag(View v, DragEvent event) <
switch(event.getAction())
<
case DragEvent.ACTION_DRAG_STARTED:
Log.d(msg, “Action is DragEvent.ACTION_DRAG_STARTED”);
// Do nothing
break;

case DragEvent.ACTION_DRAG_ENTERED:
Log.d(msg, “Action is DragEvent.ACTION_DRAG_ENTERED”);
v.invalidate();
break;

case DragEvent.ACTION_DRAG_EXITED :
Log.d(msg, “Action is DragEvent.ACTION_DRAG_EXITED”);
v.invalidate();
break;

case DragEvent.ACTION_DRAG_LOCATION :
Log.d(msg, “Action is DragEvent.ACTION_DRAG_LOCATION”);
break;

case DragEvent.ACTION_DRAG_ENDED :
Log.d(msg, “Action is DragEvent.ACTION_DRAG_ENDED”);
v.invalidate();
// Do nothing
break;

case DragEvent.ACTION_DROP:
Log.d(msg, “ACTION_DROP event”);

View view=(View) event.getLocalState();
view.setVisibility(View.VISIBLE);
view.invalidate();
return true;
default: break;
>
return true;
>
>);
>

private class DragShadow extends View.DragShadowBuilder
<

public DragShadow(View view) <
super(view);
>

@Override
public void onDrawShadow(Canvas canvas) <
super.onDrawShadow(canvas);
>

@Override
public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) <
View v= getView();

int height=v.getHeight();
int w >

shadowSize.set(width, height);
shadowTouchPoint.set((int)width/2,(int)height/2);
>

First of all I would like to say thanks for providing clear and in depth understanding of the framework. All your android tutorials are great.

I have a query, I want to get the last position to which view is dragged. As per docs getX() and getY() will not return valid value on ACTION_DRAG_ENDED. So, is there anr alternative through which I can get these values?

In simple, You are Awesome Sir .

While doing dragging, is there a way to cancel the drag operations using some external operation or is there a way to abort the dragging, without releasing the view (which is getting dragged)?

Nice Android tutorial. Really helps…

i want a bubble interface which remains on top of all layout and while moving the bubble to any image or word it copies it .the bubble does all for you . IS there any class for that.
Can you please write Android tutorial for this?

Hi , I am developed drag and drop. But, I have to reset back to previous position after dropping. Please tell me.

Sir actually i want to build dragshadow from original resources according to drag and drop of it’s original sizes .but it not happening by me if you have any solution plz mailed me .

You have given such a beautiful Android tutorial.

Comments are closed for «Android Drag and Drop».

Цукерберг рекомендует:  Обучение - выбор междцу js и php
Понравилась статья? Поделиться с друзьями:
Все языки программирования для начинающих