Breaking News

Thursday 30 January 2014

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. The framework includes following three important components to support drag & drop functionality:
  • Drag event class:
  • Drag listeners:
  • 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 callsstartDrag() 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.
S.N.Constants & Description
1ACTION_DRAG_STARTED 
Signals the start of a drag and drop operation.
2ACTION_DRAG_ENTERED 
Signals to a View that the drag point has entered the bounding box of the View.
3ACTION_DRAG_LOCATION 
Sent to a View after ACTION_DRAG_ENTERED if the drag shadow is still within the View object's bounding box.
4ACTION_DRAG_EXITED 
Signals that the user has moved the drag shadow outside the bounding box of the View.
5ACTION_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.
6ACTION_DRAG_ENDED 
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.
S.N.Constants & Description
1int getAction() 
Inspect the action value of this event..
2ClipData getClipData() 
Returns the ClipData object sent to the system as part of the call to startDrag().
3ClipDescription getClipDescription() 
Returns the ClipDescription object contained in the ClipData.
4boolean getResult() 
Returns an indication of the result of the drag and drop operation.
5float getX() 
Gets the X coordinate of the drag point.
6float getY() 
Gets the Y coordinate of the drag point.
7String toString() 
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 ClipDataobject, 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 aView.setOnLongClickListener() event listener along with View.OnDragEventListener().
StepDescription
1You will use Eclipse IDE to create an Android application and name it as DragNDropDemounder a package com.example.dragndropdemo. While creating this project, make sure youTarget SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify 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.
3Copy image logo.png in res/drawable-* folders. You can use images with different resolution in case you want to provide them for different devices.
4Modify layout XML file res/layout/activity_main.xml to define default view of the logo images.
5Run the application to launch Android emulator and verify the result of the changes done in the aplication.
Following is the content of the modified main activity filesrc/com.example.dragndropdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.dragndropdemo;

import android.os.Bundle;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipDescription;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnDragListener;
import android.widget.*;

public class MainActivity extends Activity{
   ImageView ima;
   private static final String IMAGEVIEW_TAG = "Android Logo";
   String msg;

   private android.widget.RelativeLayout.LayoutParams layoutParams;

   @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);

      ima.setOnLongClickListener(new View.OnLongClickListener() {
         @Override
         public boolean onLongClick(View v) {
            ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());

            String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
            ClipData dragData = new ClipData(v.getTag().toString(), 
            mimeTypes, item);

            // Instantiates the drag shadow builder.
            View.DragShadowBuilder myShadow = new DragShadowBuilder(ima);

            // Starts the drag
            v.startDrag(dragData,  // the data to be dragged
            myShadow,  // the drag shadow builder
            null,      // no need to use local data
            0          // flags (not currently used, set to 0)
            );
            return true;
         }
      });

      // 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:
               layoutParams = (RelativeLayout.LayoutParams) 
               v.getLayoutParams();
               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");
               int x_cord = (int) event.getX();
               int y_cord = (int) event.getY();  
               break;
            case DragEvent.ACTION_DRAG_EXITED :
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_EXITED");
               x_cord = (int) event.getX();
               y_cord = (int) event.getY();
               layoutParams.leftMargin = x_cord;
               layoutParams.topMargin = y_cord;
               v.setLayoutParams(layoutParams);
               break;
            case DragEvent.ACTION_DRAG_LOCATION  :
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_LOCATION");
               x_cord = (int) event.getX();
               y_cord = (int) event.getY();
               break;
            case DragEvent.ACTION_DRAG_ENDED   :
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENDED");
               // Do nothing
               break;
            case DragEvent.ACTION_DROP:
               Log.d(msg, "ACTION_DROP event");
               // Do nothing
               break;
            default: break;
            }
            return true;
         }
      });
   }
}
Following will be the content of res/layout/activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <ImageView
  android:id="@+id/iv_logo" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"
     android:src="@drawable/logo"
     android:contentDescription="@string/drag_drop"  />
    
</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new constants:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">DragNDropDemo</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="drag_drop">Click on the image to drag and drop</string>
   
</resources>
Following is the default content of AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.guidemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.guidemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Let's try to run your DragNDropDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Eclipse 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:
Android Drag and Drop
Now do long click on the displayed android 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 Drop to New Location

Read More

Android Google Maps Tutorial

Android allows us to integrate google maps in our application. You can show any location on the map , or can show different routes on the map e.t.c. You can also customize the map according to your choices.

Adding Google Map

Google provides this facility using google play services library which you have to download externally. After downloading , you have to integrate it with your project.In the end you have to integrate your application with google via google console. This is completely discussed in the example.

GOOGLE MAP - ACTIVITY FILE

Google provides GoogleMap and MapFragment api to integrate map in your android application. In order to use GoogleMap , you have to create an object of GoogleMap and get the reference of map from the xml layout file.Its syntax is given below:
GoogleMap googleMap;
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

GOOGLE MAP - LAYOUT FILE

Now you have to add the map fragment into xml layout file. Its syntax is given below:
<fragment
   android:id="@+id/map"
   android:name="com.google.android.gms.maps.MapFragment"
   android:layout_width="match_parent"
   android:layout_height="match_parent"/>

GOOGLE MAP - ANDROIDMANIFEST FILE

The next thing you need to do is to add some permissions along with the Google Map API key in the AndroidManifest.XML file. Its syntax is given below:
<!--Permissions-->

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<!--Google MAP API key-->

<meta-data
   android:name="com.google.android.maps.v2.API_KEY"
   android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />        

Customizing Google Map

You can easily customize google map from its default view , and change it according to your demand.

ADDING MARKER

You can place a maker with some text over it displaying your location on the map. It can be done by viaaddMarker() method. Its syntax is given below:
final LatLng TutorialsPoint = new LatLng(21 , 57);
Marker TP = googleMap.addMarker(new MarkerOptions().position(TutorialsPoint).title("TutorialsPoint")); 

CHANING MAP TYPE

You can also change the type of the MAP. There are four different types of map and each give different view of the map. These types are Normal,Hybrid,Satellite and terrain. You can use them as below
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

ENABLE/DISABLE ZOOM

You can also enable or disable the zoom gestures in the map by calling thesetZoomControlsEnabled(boolean) method. Its syntax is given below:
googleMap.getUiSettings().setZoomGesturesEnabled(true);
Apart from these customization, there are other methods availaible in the GoogleMap class , that helps you more customize the map. They are listed below:
Sr.NoMethod & description
1addCircle(CircleOptions options)
This method add a circle to the map
2addPolygon(PolygonOptions options)
This method add a polygon to the map
3addTileOverlay(TileOverlayOptions options)
This method add tile overlay to the map
4animateCamera(CameraUpdate update)
This method Moves the map according to the update with an animation
5clear()
This method removes everything from the map.
6getMyLocation()
This method returns the currently displayed user location.
7moveCamera(CameraUpdate update)
This method repositions the camera according to the instructions defined in the update
8setTrafficEnabled(boolean enabled)
This method Toggles the traffic layer on or off.
9snapshot(GoogleMap.SnapshotReadyCallback callback)
This method Takes a snapshot of the map 
10stopAnimation()
This method stops the camera animation if there is one in progress

Example

Here is an example demonstrating the use of GoogleMap class. It creates a basic M application that allows you to navigate through the map.
To experiment with this example , you can run this on an actual device or in an emulator.
StepsDescription
1Integrate google maps in your application.
2You will use Eclipse IDE to create an Android application and name it as GoogleMaps under a package com.example.googlemaps. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
3Modify src/MainActivity.java file to add necessary code.
4Modify the res/layout/activity_main to add respective XML components
5Modify AndroidManifest.xml to add necessary internet permission
6Run the application and choose a running android device and install the application on it and verify the results

Integrating Google Maps

Integrating google maps in your application basically consists of these 4 steps.
  1. Download and configure. Google Play Services SDK
  2. Obtain API key from google console
  3. Specify Android Manifest settings

Download and configure. Google Play Services SDK

INSTALL GOOGLE SERVICES SDK

Open your SDK manager in the eclipse by clicking the Window and then selecting the Android SDK manager.
Navigate to the extras tab and select the Google play services and click on install this package. It would be like this.
Anroid Google Maps Tutorial

IMPORT SDK TO ECLIPSE

After you download the SDK , click on file tab and select import option. Select existing android application code and press ok. Browse to your android folder and then sdk folder. In sdk folder expand extras folder. Expand google folder and select google play services.

CONFIGURE YOUR PROJECT WITH SDK

After you import the SDK , you have to add it into your project. For this , right click on your eclipse project and select properties. Select android from left tab and then select add from right below panel and add the project. It would be like this
Anroid Google Maps Tutorial

Obtaining the API key

This part is furthur divided into two steps. First you have to get an SHA1 fingerprint key from your pc and then you have to get map API key from google console.

GETTING CERTIFICATE FROM KEYTOOL

You need to get a certificate key because you have to provide it to google console in order to get your API key for map.
Open your command prompt and move to the path where your java jre has been placed. Now type this command.
keytool -list -v -alias androiddebugkey -keystore %%Your path%% -storepass android -keypass android
Replace the percentage part of the command with the path which you will copy from by selecting the window tab and selecting the preferences tab and then selectng the build option under android from left side.
Copy the default debug keystore path and replace it in the cmmand and hit enter. The following result would appear.
Anroid Google Maps Tutorial
Copy the SHA1 key because you need it in the next step.

GETTING KEY FROM GOOGLE CONSOLE

Open Google Console and sign in by clicking a new project.
Click on services from the left tab and then navigate to the Google Maps Android API v2. You have to turn them on like this
Anroid Google Maps Tutorial
Now again go to the left tab and select API access. And click on create new android key. Now paste the key that you copied and put a semicolon and paste your project name and click create. It would be like this.
Anroid Google Maps Tutorial
Now copy the API key that has been given to your by android , because you have to paste it into your manifest file.

Specify Android Manifest settings

The final step is to add the API key to your application. Open your manifest file and place this code right before closing the application tag.
<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="API_KEY"/>
In the second line replace API_KEY with your api key and you are done. You need to add some permissions in your manifest too which are given below in the manifest file.

Adding Google Maps to your application.

Following is the content of the modifed main activity filesrc/com.example.googlemaps/MainActivity.java.
package com.example.googlemaps;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.os.Bundle;
import android.app.Activity;
import android.widget.Toast;


public class MainActivity extends Activity {
   static final LatLng TutorialsPoint = new LatLng(21 , 57);
   private GoogleMap googleMap;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      try { 
            if (googleMap == null) {
               googleMap = ((MapFragment) getFragmentManager().
               findFragmentById(R.id.map)).getMap();
            }
         googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
         Marker TP = googleMap.addMarker(new MarkerOptions().
         position(TutorialsPoint).title("TutorialsPoint"));

      } catch (Exception e) {
         e.printStackTrace();
      }

   }

}
Following is the modified content of the xml res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent" >

   <fragment
      android:id="@+id/map"
      android:name="com.google.android.gms.maps.MapFragment"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>

</RelativeLayout>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.googlemaps"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-permission android:name="com.example.googlemaps.permission.MAPS_RECEIVE" />

   <uses-sdk
      android:minSdkVersion="12"
      android:targetSdkVersion="17" />
   <permission
      android:name="com.example.googlemaps.permission.MAPS_RECEIVE"
      android:protectionLevel="signature" />


   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
   <uses-permission android:name="android.permission.INTERNET" />
   <uses-permission android:name="com.google.android.providers.
   gsf.permission.
   READ_GSERVICES" />
   <uses-permission android:name="android.permission.
   WRITE_EXTERNAL_STORAGE" />

   <uses-permission android:name="android.permission.
   ACCESS_COARSE_LOCATION" />
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

   <uses-feature
      android:glEsVersion="0x00020000"
      android:required="true" />


   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.googlemaps.MainActivity"
         android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>


<meta-data
   android:name="com.google.android.maps.v2.API_KEY"
   android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />

   </application>

</manifest>
Let's try to run your GoogleMaps application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.
Anroid Google Maps Tutorial
Now what you need to do is to tap on the ballon to see the text.
Anroid XML Google Maps Tutorial
Now you can customize the google map according to your choice with the functions given in the GoogleMap API.
Read More
Subscribe
Labels
Popular Posts

Subscribe Via Email

About Us

THIS IS ANDROID AND JAVA FREE TUTORIAL AND ALL PROVIDE SOLUTION IN ANDROID AND JAVA INTERVIEW QUE AND ANS IS AVAILABLE IN MY BLOG AND ANY QUERY PLEASE CONTACT ME GO NOW CONTACT US PAGE.

Total Pageviews

© Android and Java solution All rights reserved | Designed By Fireandroids