Monday 10 September 2012

Multiple Views in Sinlge List with ListView and Other Control - Hotel Menu Example

In this Code We will use multiple Views in a single list as well as put a Button below the list which use to show how many items will be selected in another new Activities.



  1. First We will create the layout of each row as follows layout/rowlayout.xml.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    	android:orientation="horizontal" android:layout_width="fill_parent"
    	android:layout_height="fill_parent">
    	
    	<ImageView android:layout_height="60px" 
    		android:id="@+id/imageView1"
    		android:layout_width="60px" 
    		android:src="@drawable/icon" 
    		android:maxWidth="5px"
    		android:minWidth="5px"
    		/>
    	<TextView android:text="TextView" 
    		android:layout_width="200dp"
    		android:layout_height="wrap_content" 
    		android:id="@+id/textView1"
    		android:lines="2"
    		android:layout_marginLeft="10px"
    		android:layout_marginTop="10px" 
    		android:textSize="15px"
    		></TextView>
    	<CheckBox android:text="" 
    	android:id="@+id/checkBox1" 
    	android:layout_width="wrap_content" 
    	android:layout_height="wrap_content" />
    	
    </LinearLayout>
    
  2. Than we create our main layout as follows layout/main.xml

    <?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"
        >
    <ListView 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:id="@android:id/list"
        />
      <Button android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:id="@+id/btnOrder" 
        android:text="Order" 
        android:layout_gravity="center"/>
    </LinearLayout>
    
    Here the name of the listView must be as aboves : "@android:id/list" where android list will be automatically placed when we add the adapter in our activity class.
  3. Then we create a class which extend the ArrayAdapter  class as follows.
     
    package com.container;
    
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.CompoundButton.OnCheckedChangeListener;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    import com.container.R;
    
    public class HotelMenuAdapter extends ArrayAdapter<String> {
    	Context context;
    	String[] values;
    	int position;
    	boolean itemSelected[] = { false, false, false, false, false, false };
    
    	public HotelMenuAdapter(Context context, String[] values) {
    		super(context, R.layout.rowlayout, values);
    		this.context = context;
    		this.values = values;
    	}
    
    	public View getView(final int positon, View convertView, ViewGroup parent) {
    		LayoutInflater inflater = (LayoutInflater) context
    				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    		View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
    
    		TextView textView = (TextView) rowView.findViewById(R.id.textView1);
    		ImageView image = (ImageView) rowView.findViewById(R.id.imageView1);
    		final CheckBox checkBox = (CheckBox) rowView
    				.findViewById(R.id.checkBox1);
    
    		image.setOnClickListener(new View.OnClickListener() {
    
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				// Toast.makeText(context, ((TextView)v).getText().toString(),
    				// 5).show();
    				if (checkBox.isChecked()) {
    					checkBox.setChecked(false);
    					itemSelected[positon] = false;
    				} else {
    					checkBox.setChecked(true);
    					itemSelected[positon] = true;
    				}
    			}
    		});
    
    		textView.setOnClickListener(new View.OnClickListener() {
    
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				// Toast.makeText(context, ((TextView)v).getText().toString(),
    				// 5).show();
    				if (checkBox.isChecked()) {
    					checkBox.setChecked(false);
    					itemSelected[positon] = false;
    				} else {
    					checkBox.setChecked(true);
    					itemSelected[positon] = true;
    				}
    			}
    		});
    
    		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    
    			public void onCheckedChanged(CompoundButton buttonView,
    					boolean isChecked) {
    				// TODO Auto-generated method stub
    				// Toast.makeText(context, String.valueOf(positon), 5).show();
    				if (isChecked) {
    					itemSelected[positon] = true;
    					// Toast.makeText(context, "Checked", 5).show();
    				} else {
    
    					itemSelected[positon] = false;
    					// Toast.makeText(context, "Not Checked", 5).show();
    				}
    
    			}
    		});
    
    		textView.setText(values[positon]);
    		switch (positon) {
    		case 0:
    			image.setImageResource(R.drawable.a);
    			break;
    		case 1:
    			image.setImageResource(R.drawable.b);
    			break;
    		case 2:
    			image.setImageResource(R.drawable.c);
    			break;
    		case 3:
    			image.setImageResource(R.drawable.d);
    			break;
    		case 4:
    			image.setImageResource(R.drawable.e);
    			break;
    		case 5:
    			image.setImageResource(R.drawable.f);
    			break;
    		case 6:
    			image.setImageResource(R.drawable.g);
    			break;
    
    		}
    
    		checkBox.setChecked(false);
    		return rowView;
    	}
    
    	public boolean[] getItemSelected() {
    		return itemSelected;
    	}
    
    	public void setItemSelected(boolean[] itemSelected) {
    		this.itemSelected = itemSelected;
    	}
    
    }
    
    In this class we also add the listeners for the ImageView, TextView as well as CheckBoxes.

  4. Then in our main Activity class we will extends the ListActivity class as follows.

    package com.container;
    
    import android.app.ListActivity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.Toast;
    
    public class HotelMenuDemoActivity extends ListActivity {
    	/** Called when the activity is first created. */
    	String[] values = { "McVeggie~Rs.40-50", "McAloo Tikki~Rs 20–50",
    			"Paneer Salsa~Rs 20–50", "Crispy Chinese~Rs 20–50",
    			"McCurry Pan~Rs 20–50", "Chicken Maharaja Mac", };
    	Button btnOrder;
    	CheckBox chBox;
    	HotelMenuAdapter menuAdapter;
    
    	
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
    		
    		menuAdapter = new HotelMenuAdapter(getApplicationContext(), values);
    		setListAdapter(menuAdapter);
    
    		btnOrder = (Button) findViewById(R.id.btnOrder);
    		btnOrder.setOnClickListener(new View.OnClickListener() {
    
    			public void onClick(View arg0) {
    				// TODO Auto-generated method stub
    				boolean [] selectedItem=menuAdapter.getItemSelected();
    				int count=0;
    				Intent intent=new Intent(getApplicationContext(),ShowOrderActivity.class);
    				for(int i=0;i<selectedItem.length;i++){
    					if(selectedItem[i]==true){
    						count++;
    						intent.putExtra("items",values);
    						intent.putExtra("selected",selectedItem);
    				//	Toast.makeText(getApplicationContext(), menuAdapter.getItem(i),5).show();
    					}
    				}
    				startActivity(intent);
    			}
    		});
    
    	}
    }


  5. Finally We will create the another activity which just show the items witch is selected. as follows. 

    package com.container;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
    
    public class ShowOrderActivity extends Activity {
    
    	/** Called when the activity is first created. */
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    
    		TextView tv = new TextView(this);
    		tv.setMaxLines(10);
    		Bundle b = getIntent().getExtras();
    		String order = "Your Order is : \n";
    		String[] values = (String[]) b.getSerializable("items");
    		boolean[] items = (boolean[]) b.getSerializable("selected");
    		if (items != null && values != null) {
    			for (int i = 0; i < values.length; i++) {
    				if (items[i] == true)
    					order += values[i] + ",\n";
    			}
    		}
    		tv.setText(order);
    		setContentView(tv);
    		// TODO Auto-generated method stub
    	}
    
    }
    
That's the code:
  • When you click on the ImageView,TextView or Checkbox  corresponding Checkbox will be checked or unchecked in reverse state.  as follows

  • After selecting which ever items you want click on "Order" Button than following  output will be displayed. 

Monday 3 September 2012

Android TabLayout example


In this example we have three tab as follows. you can move in the any tab at by clicking on the Tab. as follows

  1. First we design the XML layout as follows

    <?xml version="1.0" encoding="utf-8"?>
    <TabHost xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@android:id/tabhost" android:layout_width="match_parent"
     android:layout_height="match_parent">
     <LinearLayout android:id="@+id/linearLayout1"
      android:layout_width="match_parent" android:layout_height="match_parent"
      android:orientation="vertical">
      <TabWidget android:layout_width="match_parent"
       android:layout_height="wrap_content" 
       android:id="@android:id/tabs"></TabWidget>
      <FrameLayout android:layout_width="match_parent"
       android:layout_height="match_parent" android:id="@android:id/tabcontent">
       
      </FrameLayout>
     </LinearLayout>
    </TabHost>
    
    


  2.  Create the Activtity file for diffrent Tab Activities we have create three diffrent Activity : ActivityA, ActivityB, ActivityC as follows


  3. package com.container;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
    
    public class ActivityA extends Activity {
    
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         TextView tv=new TextView(this);
         tv.setText("I am in Tab A..");
         setContentView(tv);
         // TODO Auto-generated method stub
     }
    
    }
    
    package com.container;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
    
    public class ActivityB extends Activity {
    
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         TextView tv=new TextView(this);
         tv.setText("I am in Tab B..");
         setContentView(tv);
         // TODO Auto-generated method stub
     }
    
    }
    
    package com.container;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
    
    public class ActivityC extends Activity {
    
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         TextView tv=new TextView(this);
         tv.setText("I am in Tab C..");
         setContentView(tv);
         // TODO Auto-generated method stub
     }
    
    }
    
  4. Than we Create Our main Activity as follows code..


  5. package com.container;
    
    import android.app.TabActivity;
    import android.content.Intent;
    import android.content.res.Resources;
    import android.os.Bundle;
    import android.widget.TabHost;
    
    public class TabViewDemoActivity extends TabActivity {
        /** Called when the activity is first created. */
     Resources res;
     TabHost tabHost;
     TabHost.TabSpec spec;
     Intent intent;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            res=getResources();
            tabHost=getTabHost();
            
            /**Create Tab A**/
            intent=new Intent().setClass(this,ActivityA.class);
            spec=tabHost.newTabSpec("A")
              .setIndicator("A",res.getDrawable(R.drawable.ic_btn_speak_now))
              .setContent(intent);
            tabHost.addTab(spec);
            
            /**Create Tab B**/
            intent=new Intent().setClass(this,ActivityB.class);
            spec=tabHost.newTabSpec("B")
              .setIndicator("B",res.getDrawable(R.drawable.ic_btn_speak_now))
              .setContent(intent);
            tabHost.addTab(spec);
            
            /**Create Tab C**/
            intent=new Intent().setClass(this,ActivityC.class);
            spec=tabHost.newTabSpec("C")
              .setIndicator("C",res.getDrawable(R.drawable.ic_btn_speak_now))
              .setContent(intent);
            tabHost.addTab(spec);
        }
    }


that it, Run your app you can move on any Tab By clicking on that as follows

Thursday 30 August 2012

Android Custom ArrayAdapte-ListView - Example Code

In this Example we show how to Add Multiple View in the Single Row of the ListView Control. We take two Controls ImageView and TextView as Shown follows.
  1. First We Create the layout file for the following that is as fllows : res/layout/rawlayout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="horizontal" android:layout_width="match_parent"
     android:layout_height="match_parent">
     
     <ImageView android:layout_height="wrap_content" 
      android:id="@+id/imageView1"
      android:layout_width="wrap_content" 
      android:src="@drawable/icon" />
    
     <TextView android:text="TextView" 
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" 
      android:id="@+id/textView1" 
      android:layout_marginLeft="10px"
      android:layout_marginTop="10px" 
      android:textSize="20px"
      ></TextView>
    
    </LinearLayout>
    
    

  2.  Then We Create The Custom ArrayAdapter Class Which will create by extending ArrayAdapter Class that has a getView() method that use to set how we want customize our row layout of  for each raw of ListView

    package com.container;
    
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    public class MyArrayAdapter extends ArrayAdapter<String> {
     Context context;
     String[] values;
    
     public MyArrayAdapter(Context context, String[] values) {
      super(context, R.layout.rowlayout, values);
      this.context = context;
      this.values = values;
     }
    
     public View getView(int positon, View convertView, ViewGroup parent) {
      LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
    
      TextView textView = (TextView) rowView.findViewById(R.id.textView1);
      ImageView image = (ImageView) rowView.findViewById(R.id.imageView1);
    
      textView.setText(values[positon]);
      if (positon % 2 == 0) {
       image.setImageResource(R.drawable.yes);
      } else {
       image.setImageResource(R.drawable.no);
      }
      return rowView;
     }
    }
    


  3. Then We create the Our Activity Class which extends the ListActivity class in which we have set the Adapter of using the method  setListAdapter() which has an argument of our own MyArrayAdapter class instance.


    package com.container;
    
    import android.app.ListActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.ListView;
    import android.widget.Toast;
    
    
    public class MultipleViewListActivity extends ListActivity{
        
     String [] values= {"Android", "iPhone", "WindowsMobile",
                 "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                 "Linux", "OS/2"};;
     
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            
            setListAdapter(new MyArrayAdapter(getApplicationContext(), values));
        }
    
     @Override
     protected void onListItemClick(ListView l, View v, int position, long id) {
      // TODO Auto-generated method stub
      Toast.makeText(getApplicationContext(), values[position], 5).show();
      //super.onListItemClick(l, v, position, id);
     }
    }


When you click on any of the ListItem than The Toast is appear with the Name in that TextView.


Wednesday 29 August 2012

Android GridView tutorial and Example Code


GridView:

  • Contains a horizontally scrolling list of View objects, also often used with image icons; the user can select an item to perform some action upon.
Let's take Simple Example which shows the Grid of  TextView that will be display as grid on Screen and you can select on of them. 

The Layout of this app is as follows : main.xml 

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:numColumns="2"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    />


The Java file can be as follows.

 
package com.container;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class GridViewContainerActivity extends Activity {
    /** Called when the activity is first created. */
    GridView gv;
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        String [] colors= {"Red","Green","Blue","Pink","Gray"};
        gv=(GridView)findViewById(R.id.gridView01);
        
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_gallery_item, colors);
        gv.setAdapter(adapter);
        gv.setNumColumns(3);
        gv.setBackgroundColor(Color.CYAN);
        gv.setGravity(Gravity.CENTER);
        gv.setOnItemClickListener(new OnItemClickListener() {

   public void onItemClick(AdapterView<?> myAdapter, View view, int myItemId,
     long myLang) {
    // TODO Auto-generated method stub
    
    String selectedItem=gv.getItemAtPosition(myItemId).toString();
  
    Toast.makeText(getApplicationContext(), selectedItem, 2).show();
   }
  });
    }
}

When you first run your app that will shown as follows.


 For example you select "Green" than following output will be displayed.

Android Galary Container : Code Example

Galary:

  • Contains a horizontally scrolling list of View objects, also often used with image icons; the user can select an item to perform some action upon.
Let's take Simple Example which shows the Galary of  TextView that will be scrolled horizontally and you can select on of them. 

The Layout of this app is as follows : main.xml 

<?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"
  />
  
 <Gallery android:layout_width="fill_parent"
  android:layout_height="wrap_content"
   android:id="@+id/gallary01" 
   android:spacing="100px" 
  android:layout_gravity="center"/>
</LinearLayout>

The Java file can be as follows.

 
package com.container;

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

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

   public void onItemClick(AdapterView<?> myAdapter, View view, int myItemId,
     long myLang) {
    // TODO Auto-generated method stub
    
    String selectedItem=g.getItemAtPosition(myItemId).toString();
    tv.setText("You Selected: "+ selectedItem);
    Toast.makeText(getApplicationContext(), selectedItem, 2).show();
   }
  });
    }
}

When you first run your app that will shown as follows.

 You can scroll horizontally using touch.
 For example you select "Green" than following output will be displayed.

Android Content Menu using XML file and Event Handling- 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:
  • We will override onContextItemSelected() to Listen the Item Event Selected

Context Menu with ItemListener :

  • 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>
    
  • We Create Menu using XML file res/menus/menutxt.xml for TextView as follows.. 
  • <?xml version="1.0" encoding="utf-8"?>
    <menu
      xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:id="@+id/M1"
         android:title="Menu 1" />
        <item android:id="@+id/M2"
         android:title="Menu 2" />
        <item android:id="@+id/M3"
         android:title="Menu 3" />
    </menu>
    
    
  • We Create Menu using XML file res/menus/menucm.xml for TextView as follows..
  • <?xml version="1.0" encoding="utf-8"?>
    <menu
      xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:id="@+id/menuStart"
         android:title="Start" />
        <item android:id="@+id/menuStop"
         android:title="Stop" />
        <item android:id="@+id/menuRestart"
         android:title="Restart" />
    </menu>
    
  • Then in the following Activity file in the method onCreateContextMenu() we have created Menu for TextView & Chronometer and Register for each Contrrol and using onContextItemSelected() we will listen the events of Chronometer ..
  • 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 ContextMenuXmlActivity 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
      switch(item.getItemId())
      {
       case R.id.menuStart:
        cm.start();
        break;
       case R.id.menuStop:
        cm.stop();
        break;
       case R.id.menuRestart:
        cm.setBase(android.os.SystemClock.elapsedRealtime());
        break;
      }
      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)
      {
       getMenuInflater().inflate(R.menu.menutxt, menu);
      }
      if(v.getId()==R.id.chronometer1)
      {
       getMenuInflater().inflate(R.menu.menucm, menu);
       menu.setHeaderIcon(android.R.drawable.ic_media_play);
       menu.setHeaderTitle("Timer.....");
      }
      super.onCreateContextMenu(menu, v, menuInfo);
     }
        
    }
  • When you long click on Chronometer the following ContextMenu will be displays. 
  • And you can perform "Start", "Stop" and "Restart"  the Chronometer.
  •  

Android SubMenu with Example

Submenu

  • Submenus are displayed as regular Menu Items that, when selected, reveal more items.
  • Traditionally,submenus are displayed in a hierarchical tree layout. Android uses a different approach to simplify menu navigation for small-screen devices. Rather than a tree structure, selecting a submenu presents a single floating window that displays all of its Menu Items. 
  • You can add submenus using the addSubMenu() method. It supports the same parameters as the add method used to add normal Menu Items, enabling you to specify a group, unique identifier, and text string for each submenu. You can also use the setHeaderIcon and setIcon methods to specify an iconto display in the submenu’s header bar or icon menu, respectively.

We will see an Exaple that will Display SubMenu for Background & TextColor of the Text View Whatever color you will select that will be set as Backfround and Text color respectively

  • We will create menu "Text Color" and "Text Color" and add the Sub Menu to these menus. 
  • Using menu/menus.xml file as follows.
  • <?xml version="1.0" encoding="utf-8"?>
    <menu
      xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:id="@+id/TextColor" 
         android:title="Text Color">
         <menu >
           <item android:id="@+id/TextRed" 
            android:title="Red" />
           <item android:id="@+id/TextGreen" 
            android:title="Green" />
           <item android:id="@+id/TextBlue" 
            android:title="Blue" />
         </menu> 
        </item>
        
        <item android:id="@+id/BackColor" 
         android:title="Back Color">
         <menu >
           <item android:id="@+id/BackRed" 
            android:title="Red" />
           <item android:id="@+id/BackGreen" 
            android:title="Green" />
           <item android:id="@+id/BackBlue" 
            android:title="Blue" />
         </menu> 
        </item>
        
    </menu>
    
    
  • We will write the Java code as follows.
  • package com.widget;
    
    import android.app.Activity;
    import android.graphics.Color;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.TextView;
    
    public class SubMenuXmlActivity extends Activity {
        /** Called when the activity is first created. */
        TextView tv;
     @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            tv=(TextView)findViewById(R.id.Tv01);
        }
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
      // TODO Auto-generated method stub
      getMenuInflater().inflate(R.menu.menus, menu);
      
      return super.onCreateOptionsMenu(menu);
     }
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
      // TODO Auto-generated method stub
      switch(item.getItemId())
      {
      case R.id.TextRed:
       tv.setTextColor(Color.RED);
       break;
      case R.id.TextGreen:
       tv.setTextColor(Color.GREEN);
       break;
      case R.id.TextBlue:
       tv.setTextColor(Color.BLUE);
       break;
      case R.id.BackRed:
       tv.setBackgroundColor(Color.RED);
       break;
      case R.id.BackGreen:
       tv.setBackgroundColor(Color.GREEN);
       break;
      case R.id.BackBlue:
       tv.setBackgroundColor(Color.BLUE);
       break; 
      }
      return super.onOptionsItemSelected(item);
     }
     
     
    }
    
  • The OutPut will be as follows First click on Menu Button. That will display two menu as follows
  •  Than suppose we select "Text Color" that show following Submenu for Text Color.
  •  Suppose if we select "Red" than the Text Color of TextView Will become Red.
  •  Than suppose we select "Back Color" that show following Submenu for Back Color.
  •  Suppose if we select "Green" than the Background Color of TextView Will become Green.
     

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: