Wednesday, 29 August 2012

Android ListView Tutorial with Example

ListView :

  • A view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view. 
  • Contains a vertically scrolling, horizontally filled list of View objects, each of which typically contains a row of data; the user can choose an item to perform some action upon.
  • In ListView we have set adapter of ArrayAdapter which gathers data from an Array is generally used when there is only a single column data or when the data comes from a resource array.

    Download Android ListView :Example Code

Let's see an Example of List View Simply have only one item in each line.as follows.  

First We will create a layout file main.xml as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 <TextView android:text="Select Color"
  android:id="@+id/textView1"
  android:textAppearance="?android:attr/textAppearanceLarge"
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" />
 <ListView android:layout_width="fill_parent"
  android:layout_height="wrap_content"
   android:id="@+id/listView01" />

</LinearLayout>

Than we will Create a java File as follows : 
package com.contnr;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListViewContainerActivity extends Activity {
    /** Called when the activity is first created. */
    ListView lv;
    TextView tv;
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        String [] colors= {"Red","Green","Blue","Pink","Gray"};
        lv=(ListView)findViewById(R.id.listView01);
        tv=(TextView)findViewById(R.id.textView1);
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, colors);
        lv.setAdapter(adapter);
        
        lv.setOnItemClickListener(new OnItemClickListener() {

   public void onItemClick(AdapterView<?> myAdapter, View view, int myItemId,
     long myLang) {
    // TODO Auto-generated method stub
    
    String selectedItem=lv.getItemAtPosition(myItemId).toString();
    tv.setText("You Selected: "+ selectedItem);
    Toast.makeText(getApplicationContext(), selectedItem, 2).show();
   }
  });
    }
}
When you click on any of the List Item that displayed in Toast and in TextView also as follows....

Tuesday, 28 August 2012

Android Context Menu - Example

Context Menu :

  • The ContextMenu is a subtype of Menu that you can configure to display when a long press is performed on a View. As the name implies, the ContextMenu provides for contextual menus to display to the user for performing additional actions on selected items. 
  • You need to implement the onCreateContextMenu() method of your Activity for one to display. However, before that is called, you must call the registerForContextMenu() method and pass in the View for which you want to have a context menu. This means each View on your screen can have a different context menu, which is appropriate as the menus are designed to be highly contextual. 
  • Here we have an example of a Chronometer timer, which responds to a long click with
    a context menu:
    Download Android Context Menu :Example Code
  • We have put two Control "TextView" and "Chronometer" in following main.xml file
  • <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="@string/hello"
        android:id="@+id/TV01"
        />
    <Chronometer android:text="Chronometer" 
     android:id="@+id/chronometer1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" />
    </LinearLayout>
    
  • Then in the following Activity file in the method onCreateContextMenu() we have created Menu for TextView & Chronometer and Register for each Contrrol..
  • package com.widget;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.ContextMenu;
    import android.view.ContextMenu.ContextMenuInfo;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Chronometer;
    import android.widget.TextView;
    
    public class ContextMenuActivity extends Activity {
        /** Called when the activity is first created. */
        TextView tv;
        Chronometer cm;
     @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            cm=(Chronometer)findViewById(R.id.chronometer1);
            tv=(TextView)findViewById(R.id.TV01);
            registerForContextMenu(cm);
            registerForContextMenu(tv);
            
        }
    
     @Override
     public boolean onContextItemSelected(MenuItem item) {
      // TODO Auto-generated method stub
      // Not any Task that will do with XML
      return super.onContextItemSelected(item);
     }
    
     @Override
     public void onCreateContextMenu(ContextMenu menu, View v,
       ContextMenuInfo menuInfo) {
      // TODO Auto-generated method stub
      if(v.getId()==R.id.TV01)
      {
       menu.add("Menu 1");
       menu.add("Menu 2");
       menu.add("Menu 3");
      }
      if(v.getId()==R.id.chronometer1)
      {
       menu.add("Start");
       menu.add("Stop");
       menu.add("Restart");
       menu.setHeaderIcon(android.R.drawable.ic_media_play);
       menu.setHeaderTitle("Timer....");
      }
      
      super.onCreateContextMenu(menu, v, menuInfo);
     }
        
    }
    
  • When you click on TextView & Chronotmeter that will simply display following Menu respectively. not perform any activity

Android All type of Built In Dialog Demo - Examples

This example include the following types of dialogs as follows
  • Alert Dialog Demo
  • List Dialog Demo
  • Progress Dialog Demo
  • DatePicker Dialog Demo
  • Character Picker Dialog Demo

Download Android All Dialog Demo :Example Code

  1. main.xml for this Project which Contain 5 button to call each Dialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    android:id="@+id/tvShow"
    />
    <Button android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Alert Dialog"
    android:id="@+id/btnAlert" 
    />
    
    <Button android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="List Dialog"
    android:id="@+id/btnList" 
    />
    
    <Button android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="DatePicker Dialog"
    android:id="@+id/btnDtPicker" 
    />
    
    <Button android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Progress Dialog"
    android:id="@+id/btnProgress" 
    />
    
    <Button android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Character Picker Dialog"
    android:id="@+id/btnChPicker" 
    />
    
</LinearLayout>
 
  1. Following Java Code which will display different DialogBox  when you call them using clicking Buttons. they are create as follows..
 
package com.widget;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.CharacterPickerDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AllDialogActivity extends Activity {
 /** Called when the activity is first created. */
 TextView tv;
 Button btnAlert, btnList, prgDilog = null, btnDtPicker, btnChButton;
 int year, month, day;
 CharacterPickerDialog cpd;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  tv = (TextView) findViewById(R.id.tvShow);
  cpd_init();
  /********
   * Alert Dialog Demo
   **********/
  btnAlert = (Button) findViewById(R.id.btnAlert);
  btnAlert.setOnClickListener(new View.OnClickListener() {

   public void onClick(View v) {
    // TODO Auto-generated method stub
    AlertDialog.Builder builder = new AlertDialog.Builder(
      AllDialogActivity.this);

    builder.setMessage("Are you Sure you want to Exit?");
    builder.setCancelable(false);
    builder.setPositiveButton("Yes",
      new DialogInterface.OnClickListener() {

       public void onClick(DialogInterface dialog,
         int which) {
        // TODO Auto-generated method stub
        AllDialogActivity.this.finish();
       }
      });

    builder.setNegativeButton("No",
      new DialogInterface.OnClickListener() {

       public void onClick(DialogInterface dialog,
         int which) {
        // TODO Auto-generated method stub
        dialog.cancel();
       }
      });

    AlertDialog alert = builder.create();
    alert.show();
   }
  });
  /********
   * List Dialog Demo
   **********/
  btnList = (Button) findViewById(R.id.btnList);
  btnList.setOnClickListener(new View.OnClickListener() {

   public void onClick(View v) {
    // TODO Auto-generated method stub
    AlertDialog.Builder builder = new AlertDialog.Builder(
      AllDialogActivity.this);

    CharSequence[] items = { "Red", "Green", "Blue" };
    builder.setTitle("Chose Color..");
    builder.setItems(items, new DialogInterface.OnClickListener() {

     public void onClick(DialogInterface dialog, int which) {
      // TODO Auto-generated method stub
      switch (which) {
      case 0:
       tv.setTextColor(Color.RED);
       break;
      case 1:
       tv.setTextColor(Color.GREEN);
       break;
      case 2:
       tv.setTextColor(Color.BLUE);
       break;
      }
     }
    });

    AlertDialog alert = builder.create();
    alert.show();
   }
  });

  /********
   * Progress Dialog Demo
   **********/
  prgDilog = (Button) findViewById(R.id.btnProgress);
  prgDilog.setOnClickListener(new View.OnClickListener() {

   public void onClick(View v) {
    // TODO Auto-generated method stub
    final ProgressDialog myProgressDialog = ProgressDialog.show(
      AllDialogActivity.this, "Please wait...(5sec)",
      "Doing Extreme Calculations...", true);

    new Thread() {
     public void run() {
      try {
       // Do some Fake-Work
       sleep(5000);
      } catch (Exception e) {
      }
      // Dismiss the Dialog
      myProgressDialog.dismiss();
     }
    }.start();
   }
  });

  /********
   * DatePicker Dialog Demo
   **********/
  btnDtPicker = (Button) findViewById(R.id.btnDtPicker);
  btnDtPicker.setOnClickListener(new View.OnClickListener() {

   public void onClick(View v) {
    // TODO Auto-generated method stub

    showDialog(0);
   }
  });

  /********
   * Character Picker Dialog Demo
   **********/
  btnChButton = (Button) findViewById(R.id.btnChPicker);
  btnChButton.setOnClickListener(new View.OnClickListener() {

   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    cpd_init();
    cpd.show();
   }
  });

 }

 //*** Overrided for Intialize DatePicker Dialog***/
 @Override
 protected Dialog onCreateDialog(int id) {
  Calendar c = Calendar.getInstance();
  year = c.get(Calendar.YEAR);
  month = c.get(Calendar.MONTH);
  day = c.get(Calendar.DAY_OF_MONTH);
  // TODO Auto-generated method stub
  switch (id) {
  case 0:
   return new DatePickerDialog(AllDialogActivity.this,
     datePickerListener, year, month, day);
  }
  return new DatePickerDialog(AllDialogActivity.this, datePickerListener,
    year, month, day);
 }

 //**** DatePicker Set Listener which call when we click on Set Button ****//
 private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

  // when dialog box is closed, below method will be called.
  public void onDateSet(DatePicker view, int selectedYear,
    int selectedMonth, int selectedDay) {

   year = selectedYear;
   month = selectedMonth;
   day = selectedDay;

   // set selected date into textview
   tv.setText(new StringBuilder().append(day).append("-")
     .append(month + 1).append("-").append(year).append(" "));

   // set selected date into datepicker also
   // dpResult.init(year, month, day, null);

  }
 };

 // Character Picker Dialog initialization
 void cpd_init() {
  EditText et = new EditText(this);
  et.setLayoutParams(new LinearLayout.LayoutParams(-1, -2));
  final String options = "0123456789ABCDEF";
  cpd = new CharacterPickerDialog(this, new View(this), null, options,
    false) {
   public void onClick(View v) {
    tv.setText("????:"+((Button)v).getText().toString());
    dismiss();
   }
  };

 }

} 

The Execution of Code as follows..

Initially Run the Project display the following Screen...
 Then When You Click on "Alert Dialog" Button that will show the following Dialog which ask for "Are you Sure you want to Exit" if you Press "Yes" than you will exit from this apps and if you say "No" than you will continue with this apps..
 This dialog Box will appears when you click on "List Dialog"  Button that ask you to Select any Color when you chose any color that Color will be set as Text color of TextView above displayed
 This dialog box allows you to Select a date when you select date and say "Set" that Date date set in TextView.
 This Progress Dialog box will simple wait for 5sec you can not perform any activity during this time and you can not cancel this dialog.
 This dialog Allows to you to Select any Character From this..

Wednesday, 22 August 2012

Android Option Menu using Xml file: How Create with Example

First we will create Simple Option  menus as Follows Steps

Download Android Option Menu with Xml file: Project


  1. Create a new Android Project Name MenuDemo
  2. Add XML file into res/menus/menu.xml for that follow the following Steps
    • Right Click on Project Folder 
    • Select New 
    • Select "Android XML file"
    • Give name of file As "menus"
    • Select "menu" type of Resource. 
    • Say Finish.
      Add the Following code.....

    
    
    



  1. Override the onCreateOptionMenu() Method in the Activity class files where you want to add menu. From 
    • Right click in Activity file
    • \Select ”Source”
    • Select “Override / Implement Methods “
    • Select “onCreateOptionMenu()” method
    • Say Ok.
  2. We will Use MenuInflater class to show the menus by put following code in onCreateOptionMenu()
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
     MenuInflater mi = getMenuInflater();
     mi.inflate(R.menu.menus, menu);
     return super.onCreateOptionsMenu(menu);
    }
    
  3. We will Interact with the menu Item as follows using onOptionsItemSelected() method. 
    @Override
     public boolean onOptionsItemSelected(MenuItem item) {
      // TODO Auto-generated method stub
      switch (item.getItemId()) {
      case R.id.item1:
       Toast.makeText(getApplicationContext(), "Hello!", 5).show();
       break;
      case R.id.item2:
       Intent i = new Intent(getApplicationContext(), ActivityA.class);
       startActivity(i);
       break;
      case R.id.item3:
       Intent dial = new Intent(Intent.ACTION_DIAL);
       startActivity(dial);
       break;
      default:
       break;
      }
      return super.onOptionsItemSelected(item);
     }
    

    Where We have done following actions Menu wise....
    Item1 : We wiill Display Toast "Hello"
    Item2 : We call the New Activity "Activity A"
    Item3 : We display the Default Dialer of Android.
  4. Run the Android Apps
You can Interact with Menu by clicking on all Menu Item 

  • First Click on Menu Button of Device as follows..
  • That will display the following screen as follows 
  • Press On the "Hello" that will show you Following Screen.. 
  • Then Again Press Menu Button Click on "New Activity" Item
  • Then Press Back Button. Then Again Click on "Dial" Item. that shows following Dialer.

Android Option Menu: How Create with Example

First we will create Simple Option  menus as Follows Steps

Download Android Option Menu: Project
  1. Create a new Android Project Name MenuDemoWithoutXml 
  2. Override the onCreateOptionMenu() Method in the Activity class files where you want to add menu. From 
    • Right click in Activity file
    • \Select ”Source”
    • Select “Override / Implement Methods “
    • Select “onCreateOptionMenu()” method
    • Say Ok.
  3.  Adding Menu Items into by following code
  4. package com.menu;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.Menu;
    
    public class MenuDemoWithoutXmlActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
     }
    
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
      // TODO Auto-generated method stub
      menu.add("Item 1").setIcon(android.R.drawable.btn_dialog)
        .setIntent(new Intent(this, ActivityA.class));
      menu.add("Item 2").setIcon(android.R.drawable.btn_minus);
      menu.add("Item 3").setIcon(android.R.drawable.btn_star_big_off);
      return super.onCreateOptionsMenu(menu);
     }
    }
     
This Code will just display the Simple Menu they have not any effect

For more Menu with Action we will see in following posts: