Saturday, 4 May 2013

Android Popup Menu Example

Android Popup Menu is a floating menu which displays a list of menu items on click of a view,
which has a menu associated with it.

Lets see an example of how to create popup menu .



 Project Structure :-

                    

        
Step 1
  Create XML File


create popup_menu_demo.xml containing a button view having id="popup_but_id" and text="@string/Popup_button"(naming the button) .




     File :- popup_menu_demo.xml


    






Step 2
  String Resource

 
  store menu item names inside the string.xml resource file
      File:- string.xml



    PopupMenuDemo
    Settings
    Hello world!
    Popup_Menu
    Addition
    Substraction
    Multiplication
    Division






 Step 3
Create XML for Menu

   
Create popup.xml file in res/menu and inside menu.xml file each menu item is assoicated with
  id which uniquely identifies each menu item and
  title which sets the name for menu item    

File :- popup.xml



    
    

    
    

    
    

    
    




 
Step 4
  Create Class File


create a PopupMenuDemo.class and extend it to activity class and override the onCreate() method of activity class and set the content of the actvity with the above defined xml file by call
setContentView() method and passing xml file name as a parameter to it

     setContentView(popup_menu_demo);

 
      
Step 4.1

 Inflating menu

get the id of the button with name popup

      popupbut=(Button) findViewById(R.id.menu_but);

Now to make a menu.xml file to float up on click of button view , we need to set onclicklistener for button and inside the onclick method we call PopupMenu constructor and  pass application context and button as a parameter to it

                PopupMenu popup = new PopupMenu(PopupMenuDemo.this, popup_but);
              
To inflate the menu we call inflate method on MenuInflater object .
              
                popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());

 
      Step 4.2

Responding menu item click

Now to respond to menu item click we call setOnMenuItemClickListener on PopupMenu object ,inside this method we get to know which item is clicked by user by calling
getItemId() on menuitem object .

and finally dont forget to call show() method on popup menu object
              
                 popup.show();              
                     
finally the class file would look like this

File :- PopupMenuDemo.class 

 
package com.pavan.popupmenudemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;

public class PopupMenuDemo extends Activity {

 Button popup_but;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.popup_menu_demo);
  popup_but = (Button) findViewById(R.id.popup_but_id);
  popup_but.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    PopupMenu popup = new PopupMenu(PopupMenuDemo.this, popup_but);
    popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());

    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
     public boolean onMenuItemClick(MenuItem item) {
      Toast.makeText(PopupMenuDemo.this,
        "You Clicked : " + item.getTitle(),
        Toast.LENGTH_SHORT).show();
      return true;
     }
    });

    popup.show();
   }
  });

 }

}


Step 5
 RUN














  Download Source Code     



download it PopupMenuDemo.Zip




continue reading

Wednesday, 1 May 2013

How To Create An Android Virtual Device using AVD manager In Eclipse

Before Starting this tutorial , make sure that you have installed Android SDK for Eclipse , if not than visit the tutorial on installing android SDK  


The Android tools include an emulator. The emulator behaves like a real Android device in most cases and allows you to test your application without having a real device. You can emulate one or several devices with different configurations. Each configuration is defined via an "Android Virtual Device" (AVD).


How to Create AVD ?

Even though you can use the command line tool of Android SDK to create and manage AVDs, in this tutorial I am working with Eclipse and the graphical AVD manager to create an AVD.


In Eclipse toolbar click AVD manager icon  to bring up the AVD manager.



Now, to create a new AVD. Click on the New button
 Create new Android Virtual Device (AVD) dialog pops up on click of new button
Enter the data to configure the AVD
 While making tutorial i have configured AVD with the following data
    
    Name    : smartphone
   Device    : 3.2" QVGA(ADP2)(320*480:mdpi)
   Target     : Android 4.1.2 -API Level 16

CPU/ABI  : Intel Atom(x86)

Memory options
        RAM     : 512MB
    VM Heap  :16

Internal Storage   : 200 MiB
            SD card  : 200 MiB


After entering the data click on ok



Now you can see a the AVD which you have created will be listed in Android Virtual Device Manager window , now select the AVD and click on start button


Launch Options dialog comes there click on launch button



Please wait it takes some time to emulate the emulator



now you can see  emulator



Thats it your done :)


continue reading

Thursday, 11 April 2013

Android FrameLayout Example


The Frame Layout is designed to display single item at a time , you can add multiple views inside in it,In framelayout the childviews are arranged in the form of stack ,with the most recently added view will be at the top

Lets see an example of framelayout that cantains two textview with different background color

Step 1
  Create XML File

      create a xml with framelayout view containing two textview in it with different background color

  File :-frame_layout.xml 


    
    

    
    



Inside the framelayout firstly we added textview with green background and next we added another textview with blue background so the most recently added textview that the blue background one will be displayed at top


 Step 2
  Create Class File


Create a FrameLayout.java and extend it to activity class and override the onCreate() method of activity class and set the content of the actvity with the above defined xml file by calling setContentView() method and passing xml file name as a parameter to it

                            setContentView(frame_layout);


File :- FrameLayout.class
package com.pavan.framelayoutdemo;

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

public class FrameLayout extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.frame_layout);
 }

}


Step 3
RUN

Android FrameLayout

Download Source Code



Download It FrameLayoutDemo.Zip










continue reading

Wednesday, 10 April 2013

Android Spinner View Example


In this tutorial you will see how to create spinner in android .

Project Structure




Step 1
Create XML File

Declared the spinner view in the xml file
File :- spinner_demo.xml  



      
    




Step 2
Create Class File

set the content of the activity with spinner_demo.xmls and then get the id of the spinner 
setContentView(R.layout.spinner_demo);
  sp = (Spinner) findViewById(R.id.spinner1);


Step3
Create Array Adapter 
Create ArrayAdapter Object and bind it with string array values and then set the dropdownview resource for the adapter

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, planets); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

Set the spinner view with the above declared adapter

sp.setAdapter(adapter);


Finally the class file looks like

File:- SpinnerDemo.java
package com.example.spinnerdemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class SpinnerDemo extends Activity {

 Spinner sp;
 String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars",
   "Jupiter", "Saturn", "Uranus", "Neptune" };

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  
   setContentView(R.layout.spinner_demo);
   
   sp = (Spinner) findViewById(R.id.spinner1);
   
   ArrayAdapter<string> adapter = new ArrayAdapter<string>(this,
    android.R.layout.simple_spinner_item, planets);
  
  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  
  sp.setAdapter(adapter);
  
  sp.setOnItemSelectedListener(new OnItemSelectedListener() {

   @Override
   public void onItemSelected(AdapterView arg0, View arg1,
     int position, long id) {
    // TODO Auto-generated method stub
    Toast.makeText(SpinnerDemo.this,
      "you selected: " + planets[position],
      Toast.LENGTH_SHORT).show();
   }

   @Override
   public void onNothingSelected(AdapterView arg0) {
    // TODO Auto-generated method stub

   }
  });

 }

}



Step 4
RUN


Android Spinner View


Android Spinner View


Android Spinner View




Download Source Code


Download It SpinnerDemo.Zip

continue reading

Monday, 8 April 2013

Android Title Bar Example


In this tutorial you will see the about how to remove title and also how to make an activity to occupy fullscreen .

Normally in android the activity (screen) composed of three portions they are

 1)System Tool Bar
 2)Application Title Bar
 3)Application Content



Android Activity Detail



Lets See An Example

Create XML file
File:-activity_main.xml


       
       



Create Class 
File :- MainActivity.xml
package com.pavan.removetitlebar;

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

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

 }
}


Android Activity With Title Bar



Removing Title Bar

To remove the title bar for an activity ,just go to the manifest.xml file and there under actvity tag add the following property

  android:theme="@android:style/Theme.NoTitleBar"

File:-Manifest.xml


    <uses-sdk android:minsdkversion="8" android:targetsdkversion="17">

    
        
       
        
              
                      
                        
                     
             
        
       

    




Android Remove Title Bar



Full Screen 

To make an activity to occupy device fullscreen , just go to manifest.xml file and there under activity tag add the following property

  android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

File:-Manifest.xml


    <uses-sdk android:minsdkversion="8" android:targetsdkversion="17">

    
        
             
                   
                        
                   
             
        
    




Android Activity Full Screen


continue reading

Android TimePicker Example


In this tutorial we will see about Android TimePicker Dialog  
we will see an example of selecting Time from Timepicker dialog and display it in TextView.
This dialog will disable the background activity until the user select the time and click ‘done’ tab of the dialog shown.

Firstly We get the instance of calender class and get the minute and hour of the system and set it to textview

Constructing Dialog

To construct Dialog we make use "TimePickerDialog" class , A dialog that prompts the user for the time of day using a TimePicker.

" TimePickerDialog (Context context, TimePickerDialog.OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) "

when the dialog gets prepared the onPrepareDialog(int id, Dialog dialog) is called and it updates the  time which is set by user .

Lets See An Example


Project Structure



Step 1
  Create XML File

<relativelayout android:layout_height="match_parent" android:layout_width="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".TimePicker" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">

          <textview android:id="@+id/display_id" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="" />
          

          <button android:id="@+id/change_button_id" android:layout_alignleft="@+id/display_id" android:layout_below="@+id/display_id" android:layout_height="wrap_content" android:layout_margintop="28dp" android:layout_width="wrap_content" android:text="@string/changetimebutton" />
          
</relativelayout>


Step 2
Create Class File

package com.pavan.timepickerdemo;

import java.util.Calendar;

import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class TimePicker extends Activity {

 Button change_time_but;
 TextView display_txt;
 private int mHour;
 private int mMinute;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.time_picker);
  display_txt = (TextView) findViewById(R.id.display_id);
  change_time_but = (Button) findViewById(R.id.change_button_id);
  change_time_but.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    TimePickerDialog TPD = new TimePickerDialog(TimePicker.this,
      mTimeSetListener, mHour, mMinute, false);
    TPD.show();
   }
  });
  final Calendar c = Calendar.getInstance();
  mHour = c.get(Calendar.HOUR_OF_DAY);
  mMinute = c.get(Calendar.MINUTE);

  updateDisplay();
 }

 @Override
 @Deprecated
 protected void onPrepareDialog(int id, Dialog dialog) {
  // TODO Auto-generated method stub
  super.onPrepareDialog(id, dialog);
  ((TimePickerDialog) dialog).updateTime(mHour, mMinute);
 }

 private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

  @Override
  public void onTimeSet(android.widget.TimePicker view, int hourOfDay,
    int minute) {
   // TODO Auto-generated method stub
   mHour = hourOfDay;
   mMinute = minute;
   updateDisplay();

  }
 };

 private void updateDisplay() {
  // TODO Auto-generated method stub
  display_txt.setText(new StringBuilder().append(mHour).append(":")
    .append(mMinute));
 }

}



Step 3
RUN

Android Time Picker

Android Time Picker

Download Source Code



Download It TimePickerDemo.Zip




 
continue reading

Android DatePicker Example


In this tutorial we will see about DatePicker Dialog in android
we will see an example of selecting date from datepicker dialog and display it in TextView.
This dialog will disable the background activity until the user select the date and click ‘done’ tab of the dialog shown.

Firstly We get the instance of calender class and get the month,day and year of the system and set it to textview

Constructing Dialog

To construct Dialog we make use "DatePickerDialog" class , it creates a simple dialog containing an DatePicker.

" DatePickerDialog(Context context, DatePickerDialog.OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) "

when the dialog gets prepared the onPrepareDialog(int id, Dialog dialog) is called and it updates the
date which is set by user

Lets See An Example

Project Structure





Step 1
Create XML File

File :- date_picker_demo.xml
<relativelayout android:layout_height="match_parent" android:layout_width="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".DatePickerDemo" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">

         <textview android:id="@+id/display_id" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="">
         </textview>
    
        <button android:id="@+id/change_button_id" android:layout_below="@+id/display" android:layout_height="wrap_content" android:layout_margintop="36dp" android:layout_torightof="@+id/display" android:layout_width="wrap_content" android:text="@string/changedatebutton">
        </button>

</relativelayout>


Step 2
Create Class File

File :- DatePickerDemo.class
package com.pavan.datepickerdemo;

import java.util.Calendar;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;

public class DatePickerDemo extends Activity {

 Button change_date_but;
 TextView display_txt;
 public static final int Date_dialog_id = 1;
 // date and time
 private int mYear;
 private int mMonth;
 private int mDay;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  
   setContentView(R.layout.date_picker_demo);
   
  change_date_but = (Button) findViewById(R.id.change_button_id);
  display_txt = (TextView) findViewById(R.id.display_id);
  change_date_but = (Button) findViewById(R.id.change_button_id);
  change_date_but.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
     DatePickerDialog DPD = new DatePickerDialog(
      DatePickerDemo.this, mDateSetListener, mYear, mMonth,
      mDay);
                    DPD.show();
   }
  });

  final Calendar c = Calendar.getInstance();
  mYear = c.get(Calendar.YEAR);
  mMonth = c.get(Calendar.MONTH);
  mDay = c.get(Calendar.DAY_OF_MONTH);

  updateDisplay();
 }

 @Override
 @Deprecated
 protected void onPrepareDialog(int id, Dialog dialog) {
  // TODO Auto-generated method stub
  super.onPrepareDialog(id, dialog);

  ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);

 }

 private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

  public void onDateSet(DatePicker view, int year, int monthOfYear,
    int dayOfMonth) {
   mYear = year;
   mMonth = monthOfYear;
   mDay = dayOfMonth;
   updateDisplay();
  }
 };

 private void updateDisplay() {
  // TODO Auto-generated method stub
  display_txt.setText(new StringBuilder()
    // Month is 0 based so add 1
    .append(mMonth + 1).append("-").append(mDay).append("-")
    .append(mYear));
 }

}



Step 3
RUN

Android DatePicker

Android DatePicker




Download Source Code




 Download It DatePickerDemo.Zip





continue reading
Newer Posts Home