Wednesday, May 22, 2013

Handling Keyboard Key Events

When a user gives focus on an View like  an EditText element and the user has a hardware keyboard attached, all input is handled by the system. If, however, you'd like to intercept or directly handle the keyboard input yourself, you can do so by implementing callback methods from the KeyEvent.Callback interface, such as onKeyDown() and onKeyMultiple().

Both the Activity and View class implement the KeyEvent.Callback interface, so you should generally override the callback methods in your extension of these classes as appropriate.

Handling Single Key Events

To handle an individual key press, implement onKeyDown() or onKeyUp() as appropriate. Usually, we should use onKeyUp() if you want to be sure that you receive only one event. If the user presses and holds the button, then onKeyDown() is called multiple times.

Below is just s glimpse of some keys you see the full list of keycode  List of Key Code


@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    switch (keyCode) {
 
        case KeyEvent.KEYCODE_D:
            // Your code to handle event when 'D' is pressed
            return true;
 
        case KeyEvent.KEYCODE_F:
            // Your code to handle event when 'F' is pressed
             return true;
 
        case KeyEvent.KEYCODE_J:
            // Your code to handle event when 'J' is pressed 
            return true;
 
        case KeyEvent.KEYCODE_K:
            // Your code to handle event when 'K' is pressed 
            return true;
 
        default:
            return super.onKeyUp(keyCode, event);
    }
}
 
 

Handling Modifier keys like Shift, Control



To respond to modifier key events such as when a key is combined with Shift or Control, you can
query the KeyEvent that's passed to the callback method. Several methods
provide information about modifier keys such as getModifiers()
and getMetaState(). However, the simplest solution is to check whether
the exact modifier key you care about is being pressed with methods such as
isShiftPressed() and isCtrlPressed().

Example:


 here's the onKeyDown() implementation again, with some extra handling for when the Shift key is held down with one of the keys:

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    switch (keyCode) {
        ...
        case KeyEvent.KEYCODE_J:
            if (event.isShiftPressed()) {
                // Your Code
            } else {
                 // Your Code
            }
            return true;
        case KeyEvent.KEYCODE_K:
            if (event.isShiftPressed()) {
                // Your Code
            } else {
                 // Your Code
            }
            return true;
     }
      default:
            return super.onKeyUp(keyCode, event);

 }
 

Designing For Different Screen Sizes

Android Development Tutorial


Android powers hundreds of device types with several different screen sizes, ranging from small phones to large TV sets. Therefore, it’s important that you design your application to be compatible with all screen sizes so it’s available to as many users as possible.
But being compatible with different device types is not enough. Each screen size offers different possibilities and challenges for user interaction, so in order to truly satisfy and impress your users, your application must go beyond merely supporting multiple screens: it must optimize the user experience for each screen configuration.

 Supporting Multiple Screens

  • Explicitly declare in the manifest which screen sizes your application supports

    By declaring which screen sizes your application supports, you can ensure that only devices with the screens you support can download your application. Declaring support for different screen sizes can also affect how the system draws your application on larger screens—specifically, whether your application runs in screen compatibility mode.
    To declare the screen sizes your application supports, you should include the <supports-screens> element in your manifest file.
  • Provide different layouts for different screen sizes

    By default, Android resizes your application layout to fit the current device screen. In most cases, this works fine. In other cases, your UI might not look as good and might need adjustments for different screen sizes. For example, on a larger screen, you might want to adjust the position and size of some elements to take advantage of the additional screen space, or on a smaller screen, you might need to adjust sizes so that everything can fit on the screen.
    The configuration qualifiers you can use to provide size-specific resources are small, normal, large, and xlarge. For example, layouts for an extra large screen should go in layout-xlarge/.
    Beginning with Android 3.2 (API level 13), the above size groups are deprecated and you should instead use the sw<N>dp configuration qualifier to define the smallest available width required by your layout resources. For example, if your multi-pane tablet layout requires at least 600dp of screen width, you should place it in layout-sw600dp/. Using the new techniques for declaring layout resources is discussed further in the section about Declaring Tablet Layouts for Android 3.2.
  • Provide different bitmap drawables for different screen densities

    By default, Android scales your bitmap drawables (.png, .jpg, and .gif files) and Nine-Patch drawables (.9.png files) so that they render at the appropriate physical size on each device. For example, if your application provides bitmap drawables only for the baseline, medium screen density (mdpi), then the system scales them up when on a high-density screen, and scales them down when on a low-density screen. This scaling can cause artifacts in the bitmaps. To ensure your bitmaps look their best, you should include alternative versions at different resolutions for different screen densities.
    The configuration qualifiers you can use for density-specific resources are ldpi (low), mdpi (medium), hdpi (high), and xhdpi (extra high). For example, bitmaps for high-density screens should go in drawable-hdpi/.
The size and density configuration qualifiers correspond to the generalized sizes and densities described in Range of screens supported, above.
Note: If you're not familiar with configuration qualifiers and how the system uses them to apply alternative resources, read Providing Alternative Resources for more information.
At runtime, the system ensures the best possible display on the current screen with the following procedure for any given resource:
  1. The system uses the appropriate alternative resource Based on the size and density of the current screen, the system uses any size- and density-specific resource provided in your application. For example, if the device has a high-density screen and the application requests a drawable resource, the system looks for a drawable resource directory that best matches the device configuration. Depending on the other alternative resources available, a resource directory with the hdpi qualifier (such as drawable-hdpi/) might be the best match, so the system uses the drawable resource from this directory.
  2. If no matching resource is available, the system uses the default resource and scales it up or down as needed to match the current screen size and density The "default" resources are those that are not tagged with a configuration qualifier. For example, the resources in drawable/ are the default drawable resources. The system assumes that default resources are designed for the baseline screen size and density, which is a normal screen size and a medium density. As such, the system scales default density resources up for high-density screens and down for low-density screens, as appropriate.


Screen characteristic Qualifier         Description
Size small Resources for small size screens.
normal Resources for normal size screens. (This is the baseline size.)
large Resources for large size screens.
xlarge Resources for extra large size screens.
Density ldpi Resources for low-density (ldpi) screens (~120dpi).
mdpi Resources for medium-density (mdpi) screens (~160dpi). (This is the baseline density.)
hdpi Resources for high-density (hdpi) screens (~240dpi).
xhdpi Resources for extra high-density (xhdpi) screens (~320dpi).
nodpi Resources for all densities. These are density-independent resources. The system does not scale resources tagged with this qualifier, regardless of the current screen's density.
tvdpi Resources for screens somewhere between mdpi and hdpi; approximately 213dpi. This is not considered a "primary" density group. It is mostly intended for televisions and most apps shouldn't need it—providing mdpi and hdpi resources is sufficient for most apps and the system will scale them as appropriate. If you find it necessary to provide tvdpi resources, you should size them at a factor of 1.33*mdpi. For example, a 100px x 100px image for mdpi screens should be 133px x 133px for tvdpi.
Orientation land Resources for screens in the landscape orientation (wide aspect ratio).
port Resources for screens in the portrait orientation (tall aspect ratio).
Aspect ratio long Resources for screens that have a significantly taller or wider aspect ratio (when in portrait or landscape orientation, respectively) than the baseline screen configuration.
notlong Resources for use screens that have an aspect ratio that is similar to the baseline screen configuration.




You need to create different layout for diff screen size. Support all screen you need to create following layout:
  1. Low density Small screens QVGA 240x320 (120dpi):
    layout-small-ldpi (240x320)  
    layout-small-land-ldpi (320x240)
  2. Low density Normal screens WVGA400 240x400 (x432) (120dpi):
    layout-ldpi  (240 x 400 )
    layout-land-ldpi  (400 x 240 )
  3. Medium density Normal screens HVGA 320x480 (160dpi):
    layout-mdpi (320 x 480 )
    layout-land-mdpi (480 x 320 )
  4. Medium density Large screens HVGA 320x480 (160dpi):
    layout-large-mdpi (320 x 480 )
    layout-large-land-mdpi (480 x 320)
  5. Galaxy Tab ( 240 dpi ):
    layout-large  (600 x 1024) 
    layout-large-land  (1024 x 600)
  6. High density Normal screens WVGA800 480x800 (x854) (240 dpi):
    layout-hdpi (480 x 800)
    layout-land-hdpi (800 x 480)
  7. Xoom (medium density large but 1280x800 res) (160 dpi):
    layout-xlarge (800 x 1280)
    layout-xlarge-land (1280 x 800)
Also add following code in .manifest file:

<supports-screens                                 
    android:smallScreens="true"                    
    android:normalScreens="true"         
    android:largeScreens="true"            
    android:xlargeScreens="true"             
    android:anyDensity="true" />

Tuesday, May 21, 2013

Android : Service

Service


A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding <service> declaration in its package's AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().
             Android offers the Service class to create application components specifically to handle operations and functionality that should run invisibly, without a user interface.

Unlike Activities, which present a rich graphical interface to users, Services run in the background —
updating your Content Providers, firing Intents, and triggering Notifications.


Service Class Overview


public class MyService extends Service {
   

    // Unique Identification Number for the Notification.
    // We use it on Notification start, and to cancel it.
    private int NOTIFICATION = R.string.local_service_started;

    /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
    public class LocalBinder extends Binder {
        LocalService getService() {
            return LocalService.this;
        }
    }

    @Override
    public void onCreate() {
           
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return null;
    }

    @Override
    public void onDestroy() {
        
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
 
 

Determining the cause of a system start


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if ((flags & START_FLAG_RETRY) == 0) {
// TODO If it’s a restart, do something.
}
else {
// TODO Alternative background process.
}
return Service.START_STICKY;
}


Registering a Service in the Manifest


<service android:enabled="true" android:name=".MyService"/>


Starting Service


 // Create Intent 
Intent intent=new Intent(this,MyService.class);
// start the service 
startService(intent);
 
 

Self-Terminating a Service


   stopSelf(startId);


You can read see good example of Android Service in below post. 

Android Service Example : Vibrate Service


public class VibrateService  extends Service
{

   

    @Override
            public void onStart(Intent intent, int startId) {
                // TODO Auto-generated method stub
                super.onStart(intent, startId);
               
                       
                       
                                    Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
                                    //  To  Vibrate in a pattern
                                    long pattern[]={0,800,200,1200,300,2000,400,4000};
                                    v.vibrate(pattern, -1);
                             }

        @Override
        public IBinder onBind(Intent intent)
        {
            // TODO Auto-generated method stub
            return null;
        }
      
}

Thing to Ponder:


   long pattern[]={0,800,200,1200,300,2000,400,4000}

this is pattern in which we want to Vibrate the Phone
first 0  means silent for 0 milisecond
800 means vibrate for 800 milisecond
200 means  means silent for 200 milisecond
1200  means vibrate for 1200 miliseconds

and So On.

If we do not give the Pattern Phone will vibrate in Default Manner

Customizing Checkboxes In Android

In android we can customize the customize the default checkboxes. Default checkboxes are small and also not attractive, By using customized checkboxes we can design more attractive and better user interface.

To customize checkboxes we need to define our own drawables for checked and unchecked state.

In this example I have  used these two drawables for checked and unchecked state.




We need to define the xml for our customized checkboxes

create the custom_checkbox_design.xml  file and put it in drawable folder( if drawable folder is not there ,cerate it (inside res folder, and put custom_checkbox_design.xm  file in this folder). It should look like following in pacakgae explorer

res
  -> drawable
         -> custom_checkbox_design.xml

custom_checkbox_design.xml


<?xml version="1.0" encoding="utf-8"?>
    
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
         <item android:state_checked="true" android:drawable="@drawable/checked" />
         <item android:state_checked="false" android:drawable="@drawable/unchecked" />
    
    </selector>



In checkbox  set android:button  property to the  custom_checkbox_design.xml  drawable  like
android:button="@drawable/custom_checkbox_design"

See the differences in default checkbox and customize checkbox in below screenshot.




main.xml


<LinearLayout
               android:layout_width="fill_parent"
               android:layout_height="fill_parent"
               android:orientation="vertical"
               xmlns:android="http://schemas.android.com/apk/res/android">

   <TextView
                android:id="@+id/textView1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="30dp"
                android:gravity="center_horizontal"
                android:textSize="25dp"
                android:text="Default Check box" />

  
   <!--   Default Checkboxes  -->

   <CheckBox
                   android:id="@+id/checkBoxDeafult1"
                   android:layout_width="fill_parent"
                   android:layout_height="wrap_content"
                   android:layout_gravity="center_horizontal"
                   android:text="Checked Checkbox"
                   android:layout_marginTop="20dp"
                   android:checked="true"
                   android:textSize="20dp" />
     <CheckBox
                   android:id="@+id/checkBoxDeafult1"
                   android:layout_width="fill_parent"
                   android:layout_height="wrap_content"
                   android:text="Unchecked Checkbox"
                   android:layout_marginTop="10dp"
                   android:checked="false"
                   android:textSize="20dp" />
    
    
        <View
                   android:layout_width="fill_parent"
                   android:layout_height="1dp"
                   android:layout_marginTop="20dp"
                   android:background="#B8B894" />
    
      <TextView
                   android:id="@+id/textView1"
                   android:layout_width="fill_parent"
                   android:layout_height="wrap_content"
                   android:layout_marginTop="30dp"
                   android:gravity="center_horizontal"
                   android:textSize="25dp"
                   android:text="Customized Check box" />

     
     
      <!--   Customized Checkboxes  -->

   <CheckBox
                   android:id="@+id/checkBoxCustomized1"
                   android:layout_width="fill_parent"
                   android:layout_height="wrap_content"
                   android:text="Checked Checkbox"
                   android:layout_marginTop="20dp"
                   android:checked="true"
                   android:button="@drawable/custom_checkbox_design"
                   android:textSize="20dp" />
     <CheckBox
                   android:id="@+id/checkBoxCustomized1"
                   android:layout_width="fill_parent"
                   android:layout_height="wrap_content"
                   android:text="Unchecked Checkbox"
                   android:layout_marginTop="10dp"
                   android:checked="false"
                   android:button="@drawable/custom_checkbox_design"
                   android:textSize="20dp" />
  

</LinearLayout>

Mobile Technoogy


Samsung Announces World’s First 5G mmWave Mobile Technology.


Samsung Electronics announced that it has successfully developed the world’s first adaptive array transceiver technology operating in the millimeter-wave Ka bands for cellular communications. The new technology sits at the core of 5G mobile communications system and will provide data transmission up to several hundred times faster than current 4G networks.

World’s First 5G mmWave Mobile Technology

5G mobile communications technology is the next generation of the existing 4G Long Term Evolution (4G/LTE) network technology. 5G will be capable of providing a ubiquitous Gbps experience to subscribers anywhere and offers data transmission speeds of up to several tens of Gbps per base station. 
The implementation of a high-speed 5G cellular network requires a broad band of frequencies, much like an increased water flow requires a wider pipe. While it was a recognized option, it has been long believed that the millimeter-wave bands had limitations in transmitting data over long distances due to its unfavorable propagation characteristics.
However, Samsung’s new adaptive array transceiver technology has proved itself as a successful solution. It transmits data in the millimeter-wave band at a frequency of 28GHz at a speed of up to 1.056 Gb/s to a distance of up to 2 kilometers. The adaptive array transceiver technology, using 64 antenna elements, can be a viable solution for overcoming the radio propagation loss at millimeter-wave bands, much higher than the conventional frequency bands ranging from several hundred MHz to several GHz.
Samsung plans to accelerate the research and development of 5G mobile communications technologies, including adaptive array transceiver at the millimeter-wave bands, to commercialize those technologies by 2020.



Samsung launches quad-core Galaxy Grand Quattro at Rs. 17,290


Samsung has announced the launch of the Galaxy Grand Quattro in India. This is the latest smartphone in the Galaxy Grand range, which first hit shelves earlier this year. The Galaxy Grand Quattro is powered by 1.2GHz quad-core processor, 1GB of RAM and Android 4.1.2 (Jelly Bean) preloaded. The phone has a 4.6-inch display with a resolution of 480 x 800 pixels. There is a 5MP camera with additional features like Continuous Shot, Best Photo and Color Effect. Samsung says the price of the 8GB version in India is Rs. 17,290, and it is already retailing on Samsung’s own online store for Rs 16,900. Speaking of storage, the Quattro has a memory card slot as well.
Announcing the launch of the Samsung Galaxy Grand Quattro, stated Mr Vineet Taneja, Country Head, Samsung Mobile, said: “Galaxy Grand Quattro is a revolutionary device that combines powerful performance with smart multi-tasking and advanced usability .Following the success of the Galaxy Grand introduced in January this year, we are confident that the Galaxy Grand Quattro will meet the needs of consumers looking for the ‘Grand’ experience in a slightly smaller display.”
A lot of the additional features in the Quattro are the ones seen on the higher-end Galaxy range of smartphones. The Easy Mode feature attempts to make the home screen and widgets more streamlined and easier to use for someone not very tech savvy. The Smart Alert feature lets you know about missed events such as missed calls and new messages just by picking up the phone. The device also offers Motion UI feature allowing gesture control of certain tasks.
              As a special introductory offer, the Galaxy Grand Quattro comes with a Digital Wallet of INR ,3000 valid for 90 days applicable on Games. To avail the offer the user has to SMS ‘MyOffer’ to 56886, Get a D/L link for myServices App and launch the application.

Android ProgressBar Example

ProgressBar:

ProgressBar is used to show the progress of an operation.
Visual indicator of progress in some operation. Displays a bar to the user representing how far the operation has progressed; the application can change the amount of progress (modifying the length of the bar) as it moves forward. There is also a secondary progress displayable on a progress bar which is useful for displaying intermediate progress, such as the buffer level during a streaming playback progress bar.

In this example I have shown the progress while downloading a file.


Create The xml

main..xml





<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">

   <TextView
        android:id="@+id/textView2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:gravity="center_horizontal"
        android:textSize="25dp"
        android:text="Progress Bar Example" />

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:onClick="startProgressDialog"
        android:text="Start Downloading File" />

</LinearLayout>


Note: To add a progress bar to a layout file, you can use the <ProgressBar> element. By default, the progress bar is a spinning wheel (an indeterminate indicator). To change to a horizontal progress bar, apply the Widget.ProgressBar.Horizontal style, like so:







ProgressBarActivity.java


public class ProgressBarActivity extends Activity
{
  

    Button btnStartProgress;
    ProgressDialog progressBar;
    private int progressBarStatus = 0;
    private Handler progressBarHandler = new Handler();

    private long fileSize = 0;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    }

    public void startProgressDialog(View V)
    {
       

                    // prepare for a progress bar dialog
                    progressBar = new ProgressDialog(V.getContext());
                    progressBar.setCancelable(true);
                    progressBar.setMessage("Downloading File...");
                    progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    progressBar.setProgress(0);
                    progressBar.setMax(100);
                    progressBar.show();

                    //reset progress bar status
                    progressBarStatus = 0;

                    //reset filesize
                    fileSize = 0;

                    new Thread(new Runnable() {
                        public void run() {
                            while (progressBarStatus < 100) {

                                    // process some tasks
                                progressBarStatus = fileDownloadStatus();

                                //  sleep 1 second to show the progress
                                try {
                                        Thread.sleep(1000);
                                    }
                                catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }

                                // Update the progress bar
                                progressBarHandler.post(new Runnable() {
                                    public void run() {
                                        progressBar.setProgress(progressBarStatus);
                                    }
                                });
                            }

                            // when, file is downloaded 100%,
                            if (progressBarStatus >= 100) {

                                // sleep 2 seconds, so that you can see the 100% of file download
                                try {
                                    Thread.sleep(2000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                                // close the progress bar dialog
                                progressBar.dismiss();
                            }
                        }
                    }).start();

      }


      


  //method returns the % of file downloaded
    public int fileDownloadStatus()
    {

        while (fileSize <= 1000000) {

                      fileSize++;

                       if (fileSize == 100000) {
                            return 10;
                       } else if (fileSize == 200000) {
                           return 20;
                       } else if (fileSize == 300000) {
                          return 30;
                       } else if (fileSize == 400000) {
                          return 40;
                       } else if (fileSize == 500000) {
                          return 50;
                      } else if (fileSize == 600000) {
                         return 60;
                      }
            // write your code here

        }

        return 100;

    }



Advance Android Topics


                   Customizing Toast In Android 
                   Showing Toast for Longer Time
                   Customizing the Display Time of Toast
                   Using TimePickerDialog and DatePickerDialog In android
                   Animating A Button In Android
                    Populating ListView With DataBase

                    Customizing Checkboxes In Android 
                    Increasin Size of Checkboxes
                    Android ProgressBar
                    Designing For Different Screen Sizes
                    Handling Keyboard Events 



More Android Topics:



Android : Introduction


       Eclipse Setup for Android Development

                     Configuring Eclipse for Android Development

          Begging With Android

                     Creating Your First Android Project
                     Understanding Android Manifest File of your android app


         Working With Layouts

                      Understanding Layouts in Android
                          Working with Linear Layout (With Example)
                                Nested Linear Layout (With Example)
                          Table Layout
                          Frame Layout(With Example)
                         Absolute Layout
                         Grid Layout


       Activity

                     Activity In Android
                     Activity Life Cycle
                     Starting Activity For Result
                     Sending Data from One Activity to Other in Android
                     Returning Result from Activity

     Working With Views

                     Using Buttons and EditText in Android 
                     Using CheckBoxes in Android 
                     Using AutoCompleteTextView in Android
                     Grid View

       Toast

                     Customizing Toast In Android
                     Customizing the Display Time of Toast
                     Customizing Toast At Runtime
                     Adding Image in Toast
                     Showing Toast for Longer Time

     Dialogs In Android

                     Working With Alert Dialog
                     Adding Radio Buttons In Dialog
                     Adding Check Boxes In Dialog
                     Creating Customized Dialogs in Android
                    Adding EditText in Dialog

                   Creating Dialog To Collect User Input

                 DatePicker and TimePickerDialog

                              Using TimePickerDialog and DatePickerDialog In android

    Working With SMS

                  How to Send SMS in Android
                  How To Receive SMS
                  Accessing Inbox In Android

    ListView:

               Populating ListView With DataBase

      Menus In Android

                    Creating Option Menu
                    Creating Context Menu In Android

      TelephonyManager

                    Using Telephony Manager In Android

     Working With Incoming Calls

                    How To Handle Incoming Calls in Android
                    How to Forward an Incoming Call In Android
                   CALL States In Android
 

    Miscellaneous

                   Notifications In Android
                   How To Vibrate The Android Phone
                   Sending Email In Android
                  Opening a webpage In Browser
                   How to Access PhoneBook In Android
                   Prompt User Input with an AlertDialog

   Storage:  Storing Data In Android


               Shared Prefferences  In Android

                             SharedPreferences In Android

               Files: File Handling In Android

                              Reading and Writing files to Internal Stoarage
                              Reading and Writing files to SD Card 
                           

                DataBase : Working With Database

                             Working With Database in Android
                             Creating Table In Android
                             Inserting, Deleting and Updating Records In Table in Android
                             How to Create DataBase in Android
                             Accessing Inbox In Android

     Animation In Android:

                  Animating A Button In Android




Android Custom Toast

A toast is a view containing a quick little message for the user. A toast provides simple feedback about an operation in a small popup.It only fills the amount of space required for the message and the current activity remains visible and interactive.

The default implementation of a  Toast shows a simple text at the bottom of the screen.
We can change this  default implementation of Toast , we can change the size , color, style and other properties of the text being displayed in Toast.   Not only this we show image and other views in Toast.

Toast.makeText(context,"Your Text", duration).show();


Even we can set a Layout/ View in toast and can make it more decorated.
We can also change the position of the Toast being displayed, we can display it at any place ,top, middle, left, bottom etc  of the screen.


Positioning your Toast:




A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.

For example, if you decide that the toast should appear in the top-left corner, you can set the gravity like this:
 toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

If you want to nudge the position to the right, increase the value of the second parameter. To nudge it down, increase the value of the last parameter.





Creating Layout for Custom Toast :


my_custom_toast.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/custom_toast_layout"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="8dp"
              android:background="#DAAA"
              >
    <ImageView android:src="@drawable/myimage"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginRight="8dp"
               />
    <TextView android:id="@+id/textToShow"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textColor="#FFF"
              />
</LinearLayout>


Showing The Toast



                LayoutInflater inflater = getLayoutInflater();
                // Inflate the Layout
                View layout = inflater.inflate(R.layout.my_custom_toast,
                                               (ViewGroup) findViewById(R.id.custom_toast_layout));
     
                TextView text = (TextView) layout.findViewById(R.id.textToShow);

                // Set the Text to show in TextView
                text.setText("My Custom Toast in Center of Screen");

                Toast toast = new Toast(getApplicationContext());
                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                toast.setDuration(Toast.LENGTH_LONG);
                toast.setView(layout);

                toast.show();



With the above example we can create customized toast from an xml layout, we inflate the  xml layout in our code and do the needfull.

We can also create customized toast without creating xml layout,  we can add/select the views at run time runtime and can show in the Toast. This gives us more flexibility to select the Toast Components at runtime.




                



                 // create a LinearLayout and Views

                LinearLayout  layout=new LinearLayout(this);
                layout.setBackgroundResource(R.color.LightOrange);
              
                TextView  tv=new TextView(this);
                // set the TextView properties like color, size etc
                tv.setTextColor(Color.RED);
                tv.setTextSize(15);        

                tv.setGravity(Gravity.CENTER_VERTICAL);

                // set the text you want to show in  Toast
                tv.setText("My Custom Toast at Bottom of Screen");  

               ImageView   img=new ImageView(this);

                // give the drawble resource for the ImageView
                img.setImageResource(R.drawable.myimage);


              // add both the Views TextView and ImageView in layout
                layout.addView(img);
                layout.addView(tv);

                Toast toast=new Toast(this); //context is object of Context write "this" if you are an Activity
               // Set The layout as Toast View
                toast.setView(layout);
                     
                  // Position you toast here toast position is 50 dp from bottom you can give any integral value   
                 toast.setGravity(Gravity.BOTTOM, 0, 50);
                 toast.show();




 We can also set/customize  the time interval of the Toast to show. It has been discussed in next post.



More Android Topics 


Android : Introduction


       Eclipse Setup for Android Development

                     Configuring Eclipse for Android Development

          Begging With Android

                     Creating Your First Android Project
                     Understanding Android Manifest File of your android app


         Working With Layouts

                      Understanding Layouts in Android
                          Working with Linear Layout (With Example)
                                Nested Linear Layout (With Example)
                          Table Layout
                          Frame Layout(With Example)
                         Absolute Layout
                         Grid Layout


       Activity

                     Activity In Android
                     Activity Life Cycle
                     Starting Activity For Result
                     Sending Data from One Activity to Other in Android
                     Returning Result from Activity

     Working With Views

                     Using Buttons and EditText in Android 
                     Using CheckBoxes in Android 
                     Using AutoCompleteTextView in Android
                     Grid View

       Toast

                     Customizing Toast In Android
                     Customizing the Display Time of Toast
                     Customizing Toast At Runtime
                     Adding Image in Toast
                     Showing Toast for Longer Time

     Dialogs In Android

                     Working With Alert Dialog
                     Adding Radio Buttons In Dialog
                     Adding Check Boxes In Dialog
                     Creating Customized Dialogs in Android
                    Adding EditText in Dialog

                   Creating Dialog To Collect User Input

                 DatePicker and TimePickerDialog

                              Using TimePickerDialog and DatePickerDialog In android

    Working With SMS

                  How to Send SMS in Android
                  How To Receive SMS
                  Accessing Inbox In Android

    ListView:

               Populating ListView With DataBase

      Menus In Android

                    Creating Option Menu
                    Creating Context Menu In Android

      TelephonyManager

                    Using Telephony Manager In Android

     Working With Incoming Calls

                    How To Handle Incoming Calls in Android
                    How to Forward an Incoming Call In Android
                   CALL States In Android
 

    Miscellaneous

                   Notifications In Android
                   How To Vibrate The Android Phone
                   Sending Email In Android
                  Opening a webpage In Browser
                   How to Access PhoneBook In Android
                   Prompt User Input with an AlertDialog

   Storage:  Storing Data In Android


               Shared Prefferences  In Android

                             SharedPreferences In Android

               Files: File Handling In Android

                              Reading and Writing files to Internal Stoarage
                              Reading and Writing files to SD Card 
                           

                DataBase : Working With Database

                             Working With Database in Android
                             Creating Table In Android
                             Inserting, Deleting and Updating Records In Table in Android
                             How to Create DataBase in Android
                             Accessing Inbox In Android

     Animation In Android:

                  Animating A Button In Android