Basic drag and drop

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Re: Basic drag and drop

Postby WeldFire » Wed Jul 21, 2010 3:17 am

Smills wrote:The ball will only move when i am touching the screen for some reason (doesn't matter where I am touching). It seems the draw method is only called when there is interaction. Any idea what method i can put code in to have it called every cycle?


Hey Smills,
In order for you to have to ball continusly moving all you should have to do is take it out of your onTouch method and put it else where like in a timer :D
WeldFire
Once Poster
Once Poster
 
Posts: 1
Joined: Wed Jul 21, 2010 2:58 am

Top

Re: Basic drag and drop

Postby soch12 » Wed Aug 04, 2010 1:36 am

Hi,

Thanks for a nice tutorial. Can you help me in dragging and dropping the balls from one view to another. I have a linearlyaout that has 2 views. I want to drag and drop the balls from one view to another. Balls should only fall into place if user drags them to another view otherwise the ball should come back to its original view.

Thanks in advance.
soch12
Once Poster
Once Poster
 
Posts: 1
Joined: Wed Aug 04, 2010 1:32 am

Re: Basic drag and drop

Postby amIT29 » Sat Aug 14, 2010 9:50 am

HI all this tuts is very simple and does the drag and drop just fine ..very light weight ..

I have a diff question "HOW CAN I DISABLE /RESTRICT DRAG FEATURE TO CERTAIN PART OF THE SCREEN " ??

ANY IDEAS??
amIT29
Freshman
Freshman
 
Posts: 6
Joined: Wed Aug 11, 2010 12:01 pm

Re: Basic drag and drop

Postby urbantrad » Thu Sep 09, 2010 10:24 pm

It seems that i only manage to register ACTION_DOWN events. Any idea how it comes that no other event is being passed? Could it be because of the AVD?

Code: Select all
public boolean onTouch(View arg0, MotionEvent arg1) {
   int action = arg1.getAction();
   if (action == MotionEvent.ACTION_DOWN) {
      ...
   } else {
      ...
      //never reached
   }
   return false;
}
urbantrad
Senior Developer
Senior Developer
 
Posts: 104
Joined: Thu Sep 09, 2010 10:19 pm

Re: Basic drag and drop

Postby cisco » Fri Sep 10, 2010 10:03 am

You have to return true after getting the ACTION_DOWN. You won't be notified of others actions otherwise.
cisco
Once Poster
Once Poster
 
Posts: 1
Joined: Fri Sep 10, 2010 10:01 am

Re: Basic drag and drop

Postby urbantrad » Fri Sep 10, 2010 10:43 am

lol that was pretty trivial :P I didn't have a clue what the return value was for so i just ignored it...
Thanks a lot :)

amIT29 wrote:HI all this tuts is very simple and does the drag and drop just fine ..very light weight ..

I have a diff question "HOW CAN I DISABLE /RESTRICT DRAG FEATURE TO CERTAIN PART OF THE SCREEN " ??

ANY IDEAS??


You can put an extra test on the X and Y coordinates you get from the event: for example, if you can only handle the event if the given X-coordinate is larger than say, 40:

Code: Select all
public boolean onTouchEvent(MotionEvent event) {
   int X = (int)event.getX();
   int Y = (int)event.getY();
   if (X > 40) {
       switch (eventaction ) {
          ...
       }
   }
}
urbantrad
Senior Developer
Senior Developer
 
Posts: 104
Joined: Thu Sep 09, 2010 10:19 pm

Top

Re: Basic drag and drop

Postby JimBadger » Tue Sep 14, 2010 11:49 pm

Thanks for this tutorial mate, very useful.

I too am interested in the question asked above by Soch12...how is it possible to detect if you have dragged an object into a particular view?
JimBadger
Freshman
Freshman
 
Posts: 7
Joined: Fri Jul 16, 2010 11:56 pm

Re: Basic drag and drop

Postby mod9 » Wed Jan 26, 2011 5:07 pm

Very nice and helpful sample,thanks!

I have a very strange problem with a simple modification on the code!I wanted to have the overall control of the let's say app in the activity so first i take all the code from the DrawView.class and paste it into the activity class and delete the DrawView.class file since it didn't need!everything works fine!!!
Then to seperate a little bit more the code i took all the onTouchevent code and paste it in the activity class(see the code below)!

And the strange to all this is that the onTouchevent is working(all actions up move down is being captured) but the if() statement which is checking if we are in the ball bounds doesn't!!!To be more specific it's like it can't read the X,Y vars!

When i use this(in onTouchEvent in ACTION_DOWN, the values i use here isn't the values that i was using when i was testing it i had calculate what values should i use)

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  if (20 > ball.getX() && 20< ball.getX()+50 && 30> ball.getY() && 30 < ball.getY()+50)
  2.  
Parsed in 0.030 seconds, using GeSHi 1.0.8.4


it worked!(i mean i was getting the log msg)

but when i used the original if() it didn't!!(no log msg)

code:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public class dragndrop extends Activity {
  2.     /** Called when the activity is first created. */
  3.            private ColorBall[] colorballs = new ColorBall[3]; // array that holds the balls
  4.            private static final String TAG="MyTAG";
  5.            DrawView myView;
  6.            private int balID = 0; // variable to know what ball is being dragged
  7.          
  8.     @Override
  9.     public void onCreate(Bundle savedInstanceState) {
  10.         super.onCreate(savedInstanceState);
  11.         Point point1 = new Point();
  12.                 point1.x = 50;
  13.                 point1.y = 20;
  14.                 Point point2 = new Point();
  15.                 point2.x = 100;
  16.                 point2.y = 20;
  17.                 Point point3 = new Point();
  18.                 point3.x = 150;
  19.                 point3.y = 20;
  20.                
  21.                                
  22.                 // declare each ball with the ColorBall class
  23.                 colorballs[0] = new ColorBall(this,R.drawable.bol_groen, point1);
  24.                 colorballs[1] = new ColorBall(this,R.drawable.bol_rood, point2);
  25.                 colorballs[2] = new ColorBall(this,R.drawable.bol_blauw, point3);
  26.                 myView = new DrawView(this);
  27.         setContentView(myView);
  28.     }
  29.    
  30.  // events when touching the screen
  31.     public boolean onTouchEvent(MotionEvent event) {
  32.         int eventaction = event.getAction();
  33.        
  34.        int  X = (int)event.getX();
  35.         int Y = (int)event.getY();
  36.  
  37.         switch (eventaction ) {
  38.  
  39.         case MotionEvent.ACTION_DOWN: // touch down so check if the finger is on a ball
  40.                 balID = 0;
  41.                 for (ColorBall ball : colorballs) {
  42.                 Log.d(TAG,"inside action down inside for coords:"+X+" coords: "+Y);
  43.                 Log.d(TAG,"ball coords:"+ball.getX()+" coords: "+ball.getY());
  44.                                
  45.                 if (X > ball.getX() && X < ball.getX()+50 && Y > ball.getY() && Y < ball.getY()+50){
  46.                                 Log.d(TAG,"inside ball coords!!!!!!!!!!!!!!!!!!!!!!!!:"+ball.getX()+" coords: "+ball.getY());
  47.                         balID = ball.getID();
  48.                        
  49.  
  50.                         break;
  51.                 }
  52.               }
  53.              
  54.              break;
  55.  
  56.  
  57.         case MotionEvent.ACTION_MOVE:   // touch drag with the ball
  58.                 // move the balls the same as the finger
  59.             if (balID > 0) {
  60.                 colorballs[balID-1].setX(X-25);
  61.                 colorballs[balID-1].setY(Y-25);
  62.             }
  63.                
  64.             break;
  65.  
  66.         case MotionEvent.ACTION_UP:
  67.                 // touch drop - just do things here after dropping
  68.  
  69.              break;
  70.         }
  71.         // redraw the canvas
  72.         myView.invalidate();
  73.         return true;
  74.        
  75.     }
  76.    
  77.    
  78.    
  79.    
  80.     public class DrawView extends View {
  81.        
  82.            
  83.             public DrawView(Context context) {
  84.                 super(context);
  85.                 setFocusable(true); //necessary for getting the touch events
  86.                
  87.                 // setting the start point for the balls
  88.                
  89.                
  90.             }
  91.            
  92.             // the method that draws the balls
  93.             @Override protected void onDraw(Canvas canvas) {
  94.                 //canvas.drawColor(0xFFCCCCCC);     //if you want another background color      
  95.                
  96.                 //draw the balls on the canvas
  97.                 for (ColorBall ball : colorballs) {
  98.                     canvas.drawBitmap(ball.getBitmap(), ball.getX(), ball.getY(), null);
  99.                   }
  100.  
  101.             }
  102.    
  103.     }
  104.        
  105. }
Parsed in 0.044 seconds, using GeSHi 1.0.8.4


So i came up that although they are two simple vars(X,Y) which i can take their values and print them i can't use them inside the if statement because the ontouchevent should always be inside a view.(i know it doesn't sound right,can't we have touch events which will be handled from the activity?)

Any suggestions why this is happening?
thanks!
mod9
Freshman
Freshman
 
Posts: 3
Joined: Sat Jan 22, 2011 11:47 am

Re: Basic drag and drop

Postby juninholiveira » Mon Feb 07, 2011 12:17 am

Good night guys, I'm from Brazil and I'm trying to develop a software that has the function of dragging an image coming from a file. Xml (R.layout.main), but am not able to accomplish this task. Anyone have any examples of how to do this?
Thank you very much for your help if they can collaborate.
juninholiveira
Freshman
Freshman
 
Posts: 5
Joined: Mon Feb 07, 2011 12:04 am

Re: Basic drag and drop

Postby coutant » Wed Feb 23, 2011 3:11 pm

Yes, here you explain consistently a rather direct approach. I'd call canvas oriented.
The container implements onDraw() and will draw from scratch all your items into the canvas. The item being dragged obliously get drawn att it's new position.

Another approach might be interesting too. I'd call layout-oriented. Without any onDraw() implementation. It make sense when you can consider a container with a FrameLayout. Dragging a child can be carried out by just actualizing it's LayoutParams.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public class BallView extends ImageView implements OnTouchListener {
  2.         public boolean onTouch(View v, MotionEvent event) {
  3.         FrameLayout.LayoutParams layout = (FrameLayout.LayoutParams) v.getLayoutParams();
  4.         if (event.getAction()==MotionEvent.ACTION_MOVE) {
  5.                 layout.leftMargin = (int) event.getRawX();             
  6.                 layout.topMargin = (int) event.getRawY();
  7.                }
  8.         v.setLayoutParams(layout);
  9.         return true;
  10.         }
  11.  
Parsed in 0.036 seconds, using GeSHi 1.0.8.4


We call getLayoutParams() onto the View provided by the onTouch() method.

The point is to cast it to a FrameLayout.LayoutParam.

Now you have access to the properties : leftMargin and leftMargin.
Just need to actualize them to reflect the new position, and you are done!

It's what I explain more in details in my post http://blog.scoutant.org/index.php?post/2011/02/Approche-naturelle-de-Drag-and-Drop-en-Android. In French, but you can download the code directly...
coutant
Once Poster
Once Poster
 
Posts: 1
Joined: Wed Feb 23, 2011 2:45 pm

Re: Basic drag and drop

Postby erikswed » Mon May 09, 2011 4:55 am

thanks Marchu for the tree ball code.
How would you go about to modify the code to have a TextEdit moved instead of graphic (ball).
Wanted to put text on a picture and then save it merged together as a new picture.
Moving the text around to make a "funny card" type of layout .
erikswed
Freshman
Freshman
 
Posts: 3
Joined: Sat Apr 23, 2011 6:12 pm

Re: Basic drag and drop

Postby hasanalperen » Sat May 28, 2011 3:57 pm

Thanx for sharing.
But when i openned the dragdrop application, i have to wait 2-3 seconds for dragging . If i dont wait, it gives error and the program is closed. How can i fit this problem?

Thank you very much for your help.
hasanalperen
Once Poster
Once Poster
 
Posts: 1
Joined: Fri May 27, 2011 10:01 pm

Re: Basic drag and drop

Postby ritchi3_kotzen » Fri Jun 24, 2011 7:03 am

Hi! I'm new in android and tried this sample. It works great. My problem is, how do can I add background color/image and other widgets to the app.

Thank you in advance
ritchi3_kotzen
Freshman
Freshman
 
Posts: 3
Joined: Wed Mar 30, 2011 7:41 am

Re: Basic drag and drop

Postby Aseriesofsmallprojects » Sat Dec 03, 2011 12:17 am

Great tutorial. I pushed the click evaluation code back into the object itself, so it is self-aware if a point is inside the image. I needed to do this because I loaded images that had alpha transparency.

This simplifies the code inside MotionEvent.ACTION_DOWN.

Code: Select all
/*
     * True only if the image has a non-transparent pixel at the point that was
     *  clicked.  Does NOT account for overlapping images
     */
    public boolean isIntersecting(int x, int y) {
        boolean retVal = false;
       
        int relativeX = x - mCoordX;
        int relativeY = y - mCoordY;
       
        // Only do check if the box is in the right range
        if (   (0 <= relativeX && relativeX < mImage.getWidth())
            && (0 <= relativeY && relativeY < mImage.getHeight()) ) {
            // Now, verify if the point is transparent or not
            int pixel = mImage.getPixel(relativeX, relativeY);
            int alpha = Color.alpha(pixel);

            if(0 != alpha) {
                retVal = true;
            }
        }
       
        return retVal;
    }
www.ProjectJourneyman.com - Android development and app marketing
twitter.com/PrjJourneyman Twitter feed
Android Developer Tutorial A growing tutorial for Android Devs
The Android Income Series Books on income topics for Android developers
Aseriesofsmallprojects
Developer
Developer
 
Posts: 39
Joined: Fri Oct 08, 2010 4:29 pm
Location: USA

Re: Basic drag and drop

Postby quarkbot » Sat Dec 24, 2011 4:26 pm

Thanks for the tutorial.
Very usefull
quarkbot
Once Poster
Once Poster
 
Posts: 1
Joined: Sat Dec 24, 2011 4:13 pm

Top
PreviousNext

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 10 guests