Friday, September 30, 2011

VideoView to play android exam

note: can not run emulator.You can test in device

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:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/hello"
   />
<LinearLayout
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content">
<VideoView
   android:id="@+id/myvideoview"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
///////////////////////////////////////////////
.java

package com.AnVideoView;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
public class AnVideoView extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       VideoView myVideoView = (VideoView)findViewById(R.id.myvideoview);
       myVideoView.setVideoURI(Uri.parse(SrcPath));
       myVideoView.setMediaController(new MediaController(this));
       myVideoView.requestFocus();
       myVideoView.start();
   }
}


A simple example using VideoView to play 3gp from YouTube

ScrollView android exam

ScrollView

A ScrollView is a special type of FrameLayout in that it allows users to scroll through a list of views that occupy more space than the physical display. The ScrollView can contain only one child view or ViewGroup, which normally is a LinearLayout.
Note: Do not use a ListView together with the ScrollView. The ListView is designed for showing a list of related information and is optimized for dealing with large lists.
The following main.xml content shows a ScrollView containing a LinearLayout, which in turn contains some Button and EditText views:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    android:id="@+id/widget54"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <LinearLayout
        android:layout_width="310px"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 1"
            />
        <Button
            android:id="@+id/button2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 2"
            />
        <Button
            android:id="@+id/button3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 3"
            />
        <EditText
            android:id="@+id/txt"
            android:layout_width="fill_parent"
            android:layout_height="300px"
            />
        <Button
            android:id="@+id/button4"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 4"
            />
        <Button
            android:id="@+id/button5"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 5"
            />
    </LinearLayout>
</ScrollView>
Figure 12 shows the ScrollView displaying a scroll bar on the right side of the screen. Users can drag the screen upward to reveal the views located at the bottom of the screen.

Figure 12 Using the ScrollView

FrameLayout android exam

FrameLayout

The FrameLayout is a placeholder on screen that you can use to display a single view. Views that you add to a FrameLayout is always anchored to the top left of the layout. Consider the following content in main.xml:

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
    android:id="@+id/widget68"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="40px"
        android:layout_y="35px"
        >        
        <ImageView
            android:src = "@drawable/androidlogo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </FrameLayout>
</AbsoluteLayout>
Here, you have a FrameLayout within an AbsoluteLayout. Within the FrameLayout, you embed an ImageView view. The UI is as shown in Figure 10.
Note: This example assumes that the res/drawable folder has an image named androidlogo.png.

Figure 10 Using FrameLayout
If you add another view (such as a Button view) within the FrameLayout, the view will overlap the previous view (see also Figure 11):

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
    android:id="@+id/widget68"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="40px"
        android:layout_y="35px"
        >        
        <ImageView
            android:src = "@drawable/androidlogo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />            
        <Button
            android:layout_width="124px"
            android:layout_height="wrap_content"
            android:text="Print Picture"       
            />
    </FrameLayout>
</AbsoluteLayout>

Figure 11 Overlapping views
You can add multiple views to a FrameLayout, but each will stack on top of the previous one.

RelativeLayout android exam

RelativeLayout

The RelativeLayout lets you specify how child views are positioned relative to each other. Consider the following main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/RLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <TextView
        android:id="@+id/lblComments"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Comments"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        />
    <EditText
        android:id="@+id/txtComments"
        android:layout_width="fill_parent"
        android:layout_height="170px"
        android:textSize="18sp"
        android:layout_alignLeft="@+id/lblComments"
        android:layout_below="@+id/lblComments"
        android:layout_centerHorizontal="true"
        />
    <Button
        android:id="@+id/btnSave"
        android:layout_width="125px"
        android:layout_height="wrap_content"
        android:text="Save"
        android:layout_below="@+id/txtComments"
        android:layout_alignRight="@+id/txtComments"
        />
    <Button
        android:id="@+id/btnCancel"
        android:layout_width="124px"
        android:layout_height="wrap_content"
        android:text="Cancel"
        android:layout_below="@+id/txtComments"
        android:layout_alignLeft="@+id/txtComments"
        />
</RelativeLayout>
Notice that each view embedded within the RelativeLayout have attributes that allow them to align with another view. These attributes are:

  • layout_alignParentTop
  • layout_alignParentLeft
  • layout_alignLeft
  • layout_alignRight
  • layout_below
  • layout_centerHorizontal
The value for each of these attributes is the ID for the view that you are referencing. The above XML UI creates the screen shown in Figure 9.

Figure 9 Using RelativeLayout to layout views

TableLayout android exam

TableLayout

The TableLayout groups views into rows and columns. You use the <TableRow> element to designate a row in the table. Each row can contain one or more views. Each view you place within a row forms a cell. The width for each column is determined by the largest width of each cell in that column.
Populate main.xml with the following elements and observe the UI as shown in Figure 7.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent" 
    android:layout_width="fill_parent"
    android:background="#000044">
    <TableRow> 
        <TextView 
            android:text="User Name:"
            android:width ="120px"
            />
        <EditText 
            android:id="@+id/txtUserName" 
            android:width="200px" />
    </TableRow> 
    <TableRow>
        <TextView 
            android:text="Password:"
            />
        <EditText 
            android:id="@+id/txtPassword" 
            android:password="true" 
            />
    </TableRow>
    <TableRow>
        <TextView />
        <CheckBox android:id="@+id/chkRememberPassword"
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content"
            android:text="Remember Password"
            />   
    </TableRow>
    <TableRow>
        <Button 
            android:id="@+id/buttonSignIn" 
            android:text="Log In" />
    </TableRow>
</TableLayout>

Figure 7 Using the TableLayout
Note that in the above example, there are two columns and four rows in the TableLayout. The cell directly under the Password TextView is populated with an empty element. If you don't do this, the Remember Password checkbox will then appear under the Password TextView, like that shown in Figure 8.

Figure 8 Note the change in the position of the Remember Password view

AbsoluteLayout android exam

AbsoluteLayout

The AbsoluteLayout lets you specify the exact location of its children. Consider the following UI defined in main.xml:

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <Button
        android:layout_width="188px"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_x="126px"
        android:layout_y="361px"
        />
    <Button
        android:layout_width="113px"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_x="12px"
        android:layout_y="361px"
        />
</AbsoluteLayout>
Figure 6 shows the two Button views located at their specified positions using the android_layout_x and android_layout_y attributes.

Figure 6 Views laid out using AbsoluteLayout
Author's Note. You should ideally use AbsoluteLayout when you need to reposition your views when there is a change in the screen rotation.

LinearLayout android exam

LinearLayout

The LinearLayout arranges views in a single column or single row. Child views can either be arranged vertically or horizontally. To see how LinearLayout works, let's modify the main.xml file in the project:

<?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"
        />
</LinearLayout>
In the main.xml file, observe that the root element is <LinearLayout> and it has a <TextView> element contained within it. The <LinearLayout> element controls the order in which the views contained within it appear.
Each View and ViewGroup has a set of common attributes, some of which are shown in Table 1.
AttributeDescription
layout_widthSpecifies the width of the View or ViewGroup
layout_heightSpecifies the height of the View or ViewGroup
layout_marginTopSpecifies extra space on the top side of the View or ViewGroup
layout_marginBottomSpecifies extra space on the bottom side of the View or ViewGroup
layout_marginLeftSpecifies extra space on the left side of the View or ViewGroup
layout_marginRightSpecifies extra space on the right side of the View or ViewGroup
layout_gravitySpecifies how child Views are positioned
layout_weightSpecifies how much of the extra space in the layout to be allocated to the View
layout_xSpecifies the x-coordinate of the View or ViewGroup
layout_ySpecifies the y-coordinate of the View or ViewGroup
Table 1 Common attributes of views and viewgroups
Note that some of these attributes are only applicable when a View is in certain specific ViewGroup(s). For example, the layout_weight and layout_gravity attributes are only applicable if a View is either in a LinearLayout or TableLayout.
For example, the <TextView> element above has its width filling up the entire width of its parent (which is the screen in this case) using the fill_parent constant. Its height is indicated by the wrap_content constant, which means that its height is the height of its content (in this case, the text contained within it). If you do not wish to have the <TextView> view occupy the entire row, you can set its layout_width attribute to wrap_content, like this:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
This will set the width of the view to be equal to the width of the text contained within it. You can also set the width to an absolute value, like this:

<TextView
    android:layout_width="105px"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
In this case, the width is set to 105 pixels wide. Let's modify the main.xml file by adding a <Button> view as shown below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <TextView
        android:layout_width="105px"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        />
    <Button
        android:layout_width="100px"
        android:layout_height="wrap_content"
        android:text="Button"
        />
</LinearLayout>

WebView android exam

The WebView view allows you to embed a web browser in your Android applications. Add a new file to the res/layout folder and name it as webview.xml and populate it with the following element:
<?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"
    >
 
    <WebView android:id="@+id/webview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:text = "Hello, world!"
        />            
 
</LinearLayout>
Add a new class to the src/net.learn2develop.AndroidViews folder and name it as WebViewExample.java. Populate it as follows:
package net.learn2develop.AndroidViews;
 
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
 
public class WebViewExample extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);
 
        WebView wv = (WebView) findViewById(R.id.webview1);        
        wv.loadUrl("http://www.mobiforge.com");  
    }
}
The loadUrl() method of the WebView class loads the page of a given URL. Modify the AndroidManifest.xml file to register the new activity as well as to request for the INTERNET permission:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.AndroidViews"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ViewsActivity" 
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 
        <activity android:name=".WebViewExample"
                  android:label="@string/app_name" />
 
    </application>
 
    <uses-permission android:name="android.permission.INTERNET">
    </uses-permission>
 
   <uses-sdk android:minSdkVersion="3" />
 
</manifest>
For the WebView view to work, you need to add the INTERNET permission to the AndroidManifest.xml file. Modify the ViewsActivity.java file as follows to start the WebViewExample activity:
package net.learn2develop.AndroidViews;
 
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
 
public class ViewsActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);      
        startActivity(new Intent(this, WebViewExample.class));
    }
}
Press F11 to debug the application on the Android emulator. Figure 8 shows the WebView view in action.

Figure 8 - The WebView displaying a web page
You can also dynamically formulate a HTML string and load it into the WebView view, using the loadDataWithBaseURL() method:
 
  WebView wv = (WebView) findViewById(R.id.webview1);        
 
        final String mimeType = "text/html";
        final String encoding = "UTF-8";
        String html = "<H1>A simple HTML page</H1><body>" +
            "<p>The quick brown fox jumps over the lazy dog</p>"; 
 
        wv.loadDataWithBaseURL("", html, mimeType, encoding, "");
Figure 9 shows the WebView with the HTML string loaded.

Figure 9 - Displaying the content of a HTML string
If you have static pages that you want to load directly from your project, you can save the HTML pages under the assets folder of your package. Figure 10 shows that I have added a page named Index.html under the assets folder.

Figure 10 - Adding a HTML page in the assets folder
The content of the Index.html is as follows:
<h1>A simple HTML page</h1>
<body>
   <p>The quick brown fox jumps over the lazy dog</p>
   <img src='http://www.google.com/logos/Logo_60wht.gif'/>
</body>
To load the WebView using the content stored in the Index.html file, use the loadUrl() method as follows:
WebView wv = (WebView) findViewById(R.id.webview1);     
     wv.loadUrl("file:///android_asset/Index.html");
Figure 11 shows the content loaded in the WebView view.

Figure 11 - Loading the HTML page using WebView

AnalogClock and DigitalClock Views android exam

The AnalogClock view displays an analog clock. Populate the main.xml file with the following element:
<?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"
    >  
 
    <AnalogClock android:id="@+id/clock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
 
</LinearLayout>
In the ViewsActivity.java file, ensure that the main.xml file is loaded as the UI for the activity:
package net.learn2develop.AndroidViews;
 
import android.app.Activity;
import android.os.Bundle;
 
public class ViewsActivity extends Activity 
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
 
    }
}
When you press F11 now, you will see the analog clock as shown in Figure 6.

Figure 6 - The AnalogClock in action
Instead of an analog clock, you can display a digital clock instead using the DigitalClock view.
Add the DigitalClock element to main.xml as shown below:
<?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"
    >  
 
    <AnalogClock android:id="@+id/clock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
    <DigitalClock android:id="@+id/clock2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />            
 
</LinearLayout>
Press F11 in Eclipse. Figure 7 shows the analog clock and the digital clock.

Figure 7 - The DigitalClock in action

AnalogClock and DigitalClock Views android exam

Besides the standard views that you have seen up to this point, the Android SDK also provides some interesting views that make your applications much more interesting. In the following sections, you will learn more about the following views:
  • AnalogClock
  • DigitalClock
  • WebView

AnalogClock and DigitalClock Views

The AnalogClock view displays an analog clock. Populate the main.xml file with the following element:
<?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"
    >  
 
    <AnalogClock android:id="@+id/clock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
 
</LinearLayout>
In the ViewsActivity.java file, ensure that the main.xml file is loaded as the UI for the activity:
package net.learn2develop.AndroidViews;
 
import android.app.Activity;
import android.os.Bundle;
 
public class ViewsActivity extends Activity 
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
 
    }
}
When you press F11 now, you will see the analog clock as shown in Figure 6.

Figure 6 - The AnalogClock in action
Instead of an analog clock, you can display a digital clock instead using the DigitalClock view.
Add the DigitalClock element to main.xml as shown below:
<?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"
    >  
 
    <AnalogClock android:id="@+id/clock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
    <DigitalClock android:id="@+id/clock2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />            
 
</LinearLayout>
Press F11 in Eclipse. Figure 7 shows the analog clock and the digital clock.

Figure 7 - The DigitalClock in action

Context Menu android exam

If you want to associate a context menu to a view on an activity, you need to call the setOnCreateContextMenuListener() method of that particular view. For example, the following code shows how you can associate a context menu with the Button view:
package net.learn2develop.AndroidViews;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.Toast;
 
public class MenuExample extends Activity
{    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);        
        setContentView(R.layout.menu);      
 
        Button btn = (Button) findViewById(R.id.btn1);        
        btn.setOnCreateContextMenuListener(this);
    }
 
    private void CreateMenu(Menu menu)
    {
        //...
    }
 
    private boolean MenuChoice(MenuItem item)
    {        
        //...
    }
 
    //---only created once---
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        super.onCreateOptionsMenu(menu);
        CreateMenu(menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {    
         return MenuChoice(item);    
    }
 
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, 
    ContextMenuInfo menuInfo) 
    {
         super.onCreateContextMenu(menu, view, menuInfo);
         CreateMenu(menu);
    }
 
    @Override
    public boolean onContextItemSelected(MenuItem item)
    {    
         return MenuChoice(item);    
    }    
 
}

Options Menu

To display the options menu for your activity, you need to override two methods – onCreateOptionsMenu() and onOptionsItemSelected(). The onCreateOptionsMenu() method is called when the MENU button is pressed. In this event, you would call the CreateMenu() helper method to display the options menu. When a menu item is selected, the onOptionsItemSelected() method will be called. In this case, you call the MenuChoice() method to display the menu item selected (and do whatever you need to do):
public class MenuExample extends Activity
{    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
 
        setContentView(R.layout.menu);        
    }
 
    private void CreateMenu(Menu menu)
    {
        //...
    }
 
    private boolean MenuChoice(MenuItem item)
    {        
        //...
    }    
 
    //---only created once---
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        CreateMenu(menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {    
         return MenuChoice(item);    
    }
 
}
Modify the ViewsActivity.java file as follows to start the MenuExample activity:
package net.learn2develop.AndroidViews;
 
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
 
public class ViewsActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        startActivity(new Intent(this, MenuExample.class));
    }
}
Press F11 to debug the application. When you press the MENU key, you will see the options menu as shown in Figure 4.

Figure 4 - Displaying a options menu in your application
Observe the icons displayed for menu item 1, 2 and 3. Also, if the options menu has more than six items, there will be a More menu item to represent the additional menu items. The right of Figure 3-24 shows pressing the More item displays the additional menu items as a list.

Creating the Helper Methods android exam

For the examples in this section, you will create two helper methods in the MenuExample.java file. They are CreateMenu() and MenuChoice(). Define the two helper methods and the onCreate() method as shown below:

package net.learn2develop.AndroidViews;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;

public class MenuExample extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

setContentView(R.layout.menu);
Button btn = (Button) findViewById(R.id.btn1);
btn.setOnCreateContextMenuListener(this);
}

private void CreateMenu(Menu menu)
{
menu.setQwertyMode(true);
MenuItem mnu1 = menu.add(0, 0, 0, "Item 1");
{
mnu1.setAlphabeticShortcut('a');
mnu1.setIcon(R.drawable.alert_dialog_icon);
}
MenuItem mnu2 = menu.add(0, 1, 1, "Item 2");
{
mnu2.setAlphabeticShortcut('b');
mnu2.setIcon(R.drawable.ic_popup_reminder);
}
MenuItem mnu3 = menu.add(0, 2, 2, "Item 3");
{
mnu3.setAlphabeticShortcut('c');
mnu3.setIcon(R.drawable.icon);
}
MenuItem mnu4 = menu.add(0, 3, 3, "Item 4");
{
mnu4.setAlphabeticShortcut('d');
}
menu.add(0, 3, 3, "Item 5");
menu.add(0, 3, 3, "Item 6");
menu.add(0, 3, 3, "Item 7");
}

private boolean MenuChoice(MenuItem item)
{
switch (item.getItemId()) {
case 0:
Toast.makeText(this, "You clicked on Item 1",
Toast.LENGTH_LONG).show();
return true;
case 1:
Toast.makeText(this, "You clicked on Item 2",
Toast.LENGTH_LONG).show();
return true;
case 2:
Toast.makeText(this, "You clicked on Item 3",
Toast.LENGTH_LONG).show();
return true;
case 3:
Toast.makeText(this, "You clicked on Item 4",
Toast.LENGTH_LONG).show();
return true;
case 4:
Toast.makeText(this, "You clicked on Item 5",
Toast.LENGTH_LONG).show();
return true;
case 5:
Toast.makeText(this, "You clicked on Item 6",
Toast.LENGTH_LONG).show();
return true;
case 6:
Toast.makeText(this, "You clicked on Item 7",
Toast.LENGTH_LONG).show();
return true;
}
return false;
}
}

The CreateMenu() method creates a list of menu items and modifies the behavior of each menu item. The parameters for the add() method are: groupid, itemid, order, and title. The setAlphabeticShortcut() method assigns a keyboard shortcut to the menu item so that when the user presses a specific key, the menu item would be selected. The setIcon() method assigns an icon to the menu item.

The MenuChoice() method displays the selected menu item using the Toast class. Next, copy two images (as shown in Figure 3) into the res/drawable folder.


Figure 3 - Adding images to the res/drawable folder