Pages

Saturday, September 29, 2012

Add Menu to Your Android Application...

Menus are most common user interface in many types of applications.To provide a familiar and consistent user experience you should use the Menu APIs to present the user actions and other options in your activity. I'll tell you how you can add Menu to your Android Application.

Application Overview

In this application I have created a Menu named COLOR which has a SubMenu, the list of colors. The background color of the screen as per selection of color from SubMenu.


1. Design Screen

Take a TextView control on the screen and set height and with of the control to MATCH_PARENT.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
        <TextView
            android:id="@+id/screen"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout> 
The TextView in this program represent entire screen. On the selection of color from Menu the background color of TextView will change as well. 2. Write Class File  I'll add menu to the application programmatically. Take a look at below Java code of the Activity name MenuDemo.  
 package androidrises.menudemo;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.TextView;

public class MenuDemo extends Activity {

 private static final int COLOR = 0;
 
 private static final int RED = Menu.FIRST;
 private static final int GREEN = RED+1;
 private static final int BLUE = GREEN+1;
 private static final int YELLOW = BLUE+1;
 TextView screen;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu_demo);
        
        screen = (TextView)findViewById(R.id.screen);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_menu_demo, menu);
        
        SubMenu sm = menu.addSubMenu("Color");
        
        sm.add(COLOR, RED, 0, "Red");
        sm.add(COLOR, BLUE, 1, "Blue");
        sm.add(COLOR, GREEN, 2, "Green");
        sm.add(COLOR, YELLOW, 3, "Yellow");

        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
     // TODO Auto-generated method stub
     switch (item.getItemId()) {
  case RED:
   screen.setBackgroundColor(Color.RED);
   break;
  case BLUE:
   screen.setBackgroundColor(Color.BLUE);
   break;
  case YELLOW:
   screen.setBackgroundColor(Color.YELLOW);
   break;
  case GREEN:
   screen.setBackgroundColor(Color.GREEN);
   break;

  default:
   break;
  }
     return super.onOptionsItemSelected(item);
    }
}
This is the main Activity class where I have created Menu. Method onCreateMenu will add Manu to your application.

public boolean onCreateOptionsMenu(Menu menu) 
{
     getMenuInflater().inflate(R.menu.activity_menu_demo, menu);
        
     SubMenu sm = menu.addSubMenu("Color");
        
     sm.add(COLOR, RED, 0, "Red");
     sm.add(COLOR, BLUE, 1, "Blue");
     sm.add(COLOR, GREEN, 2, "Green");
     sm.add(COLOR, YELLOW, 3, "Yellow");
     return true;
}

SubMenu sm = menu.addSubMenu("Color") will create a Menu in which we can add some more Menu as SubMenu. sm.dd(int groupID, int itemID, int order, CharSequence title) will add an item to Menu sm.
First argument is group id that is item should be part of. This can be define group of items for batch state changes. You can set NONE if you don't want to put item as part of any group.
Second argument is item id which is unique. You can set NONE if you don't want to keep id for item.
Third argument is the order of the items you want to keep.
Fourth is the title of that Menu item.

This all will create a Menu named Color with SubMenu having four items as color names.

 public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
        case RED:
            screen.setBackgroundColor(Color.RED);
            break;
        case BLUE:
            screen.setBackgroundColor(Color.BLUE);
            break;
        case YELLOW:
            screen.setBackgroundColor(Color.YELLOW);
            break;
        case GREEN:
            screen.setBackgroundColor(Color.GREEN);
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }

This method will execute on selection of item from the Menu.

onOptionsItemSelected(MenuItem item) is the method will execute on selection of Menu item and the item user have clicked, will pass to this method as parameter.

We can catch the id of that particular item as given below.
item.getItemId()

I have match id with all four ids I have created and in each case statement I have set the background color of the TextView as per item selected.

Thats it! You are done.

Screens:




   




Wednesday, September 19, 2012

AndroidManifest.xml

Every Android application must have an Androidmanifest.xml file in its root directory. The manifest presents essential information about the application to the Android system, information the system must have before it can run any of the application's code. The components and settings describes in Androidmanifest.xml file.

If you are using Eclipse, you'll find five tabs after opening this file.
  1. Manifest
  2. Application
  3. Permissions
  4. Instrumentation
  5. Androidmanifest.xml


    
        
            
                
                
            
        

    
    

 

Let's understand above code of Androidmanifest.xml file.
<manifest>
The root element of the AndroidManifest.xml file. It must contain an <application> element and specify xmlns:android and package attributes.
 
Attributes

xmlns:android
Defines the Android namespace. This attribute should always be set to "http://schemas.android.com/apk/res/android".

package
A full Java-language-style package name for the application. The name should be unique. The name may contain uppercase or lowercase letters ('A' through 'Z'), numbers, and underscores ('_'). However, individual package name parts may only start with letters.
 
To avoid conflicts with other developers, you should use Internet domain ownership as the basis for your package names (in reverse). For example, applications published by Google start with com.google. You should also never use the com.example namespace when publishing your applications.
 
The package name serves as a unique identifier for the application. It's also the default name for the application process (see the <application> element's process process attribute) and the default task affinity of an activity (see the <activity> element's taskAffinity attribute).
 
android:sharedUserId
The name of a Linux user ID that will be shared with other applications. By default, Android assigns each application its own unique user ID. However, if this attribute is set to the same value for two or more applications, they will all share the same ID — provided that they are also signed by the same certificate. Application with the same user ID can access each other's data and, if desired, run in the same process.

android:sharedUserLabel
A user-readable label for the shared user ID. The label must be set as a reference to a string resource; it cannot be a raw string.
This attribute was introduced in API Level 3. It is meaningful only if the sharedUserId attribute is also set.

android:versionCode
An internal version number. This number is used only to determine whether one version is more recent than another, with higher numbers indicating more recent versions. This is not the version number shown to users; that number is set by the versionName attribute. 

The value must be set as an integer, such as "100". You can define it however you want, as long as each successive version has a higher number. For example, it could be a build number. Or you could translate a version number in "x.y" format to an integer by encoding the "x" and "y" separately in the lower and upper 16 bits. Or you could simply increase the number by one each time a new version is released.

android:versionName
The version number shown to users. This attribute can be set as a raw string or as a reference to a string resource. The string has no other purpose than to be displayed to users. The versionCode attribute holds the significant version number used internally.

android:installLocation
The default install location for the application.



Manifest tab
The manifest tab contains package-wide settings, including the package name, version information, and supported Android SDK information. You can also set any hardware or feature requirements here.

Application tab
The application tab contains application-wide settings, including the application label and icon, as well as information about the application components such as activities, intent filters, and other application components, including configuration for services, intent filters, and content providers.

Permission tab
The permission tab contain any permission rules required by your application. This tab can also be used to enforce custom permissions created for the application.

Instrumentation tab
The instrumentation tab allows the developer to declare any instrumentation classes for monitoring the application.
Androidmanifest.xml
This tab you can use to edit all above tab manually.



    

          

                      

                      

                  

Here's summary of above xml file. 
  • The application uses the package name com.android.multimedia
  • The application version name 1.0
  • The application version code 1
  • The application name and label are stored in resource string called @string/app_name within the /res/values/string.xml resource file.
  • The application is debuggable on an Android device.
  • The application icon is the graphic file called icon (could be a PNG, JPG, or GIF) stored within the /res/drawable directory
  • The application has five activities
    • MultimediaMenuActivity
    • AudioActivity
    • StillImageActivity
    • VideoPlayActivity
    • VideoRecordActivity
  • MultimediaMenuActivity is the primary entry point for the application. This is the activity that starts when the application icon is pressed in the application drawer.
  • The application requires the following permission to run: the ability to record audio, the ability to set the wallpaper on the device, the ability to access the built-in camera, and the ability to write settings.
  • The application works from any API level from 3 to 8; in other words, Android SDK 1.5 is the lowest supported, and the application was written to target android 2.2.
  • Finally, the application requires a camera to work properly.

ImageView attributes & methods

ImageView

Displays an arbitrary image, such as an icon. The ImageView class can load images from various sources (such as resources or content providers), takes care of computing its measurement from the image so that it can be used in any layout manager, and provides various display options such as scaling and tinting.


XML Attributes

android:adjustViewBounds

Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable. 
Must be a boolean value, either "true" or "false".
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:]type:name" containing a value of this type. 

android:cropToPadding

If true, the image will be cropped to fit within its padding.  
Must be a boolean value, either "true" or "false".
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:]type:name" containing a value of this type. 


android:maxHeight

An optional argument to supply a maximum height for this view. 

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). 


android:maxWidth

An optional argument to supply a maximum width for this view.

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).


android:src

Sets a drawable as the content of this ImageView.
May beme attribute in the form "?[package:]type:name".
May be a color value, in the form of "#rgb", "#argb","#rrggbb","#aarrggbb".



Methods 

public void setAdjustViewBounds(boolean adjustViewBounds)

Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable.
Parameters
adjustViewBounds   Whether to adjust the bounds of this view to presrve the original aspect ratio of the drawable

public void setCropToPadding(boolean cropToPadding)

Sets whether this ImageView will crop to padding.
Parameters
cropToPadding whether this ImageView will crop to padding

public void setImageBitmap(Bitmap bm)

Sets a Bitmap as the content of this ImageView.
Parameters
bm The bitmap to set 

public void setImageDrawble(Drawble drawble)


Sets a drawable as the content of this ImageView. 
Parameters
drawable The drawable to set







public void setMaxHeight(int maxHeight)


An optional argument to supply a maximum height for this view. Only valid if setAdjustViewBounds(boolean) has been set to true. To set an image to be a maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width layout params to WRAP_CONTENT.

Note that this view could be still smaller than 100 x 100 using this approach if the original image is small. To set an image to a fixed size, specify that size in the layout params and then use setScaleType(android.widget.ImageView.ScaleType) to determine how to fit the image within the bounds.

Parameters
maxHeight maximum height for this view

public void setMaxWidth(int maxWidth)


An optional argument to supply a maximum width for this view. Only valid if setAdjustViewBounds(boolean) has been set to true. To set an image to be a maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width layout params to WRAP_CONTENT.

Note that this view could be still smaller than 100 x 100 using this approach if the original image is small. To set an image to a fixed size, specify that size in the layout params and then use setScaleType(android.widget.ImageView.ScaleType) to determine how to fit the image within the bounds.
Parameters
maxWidth maximum width for this view

public void setImageResource(int resid)


Sets a drawable as the content of this ImageView.

This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using setImageDrawable(android.graphics.drawable.Drawable) or setImageBitmap(android.graphics.Bitmap) and BitmapFactory instead.
Parameters
resId  the resource identifier of the the drawable










Saturday, September 15, 2012

Attributes, Methods and Events for TextView, EditText and Button



TextView: Displays text to the user and optionally allows them to edit it.

EditText: EditText is a thin veneer over TextView that configures itself to be editable.

Button: Represents a push-button widget. Push-buttons can be pressed, or clicked, by the user to perform an action. 


XML Attributes & related Methods

Attribute Name Related Method Description
android:ems setEms(int) Makes the TextView be exactly this many ems wide. An em is a unit of measurement in the field of typography, equal to the currently specified point size.
android:gravity setGravity(int) Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than the view. 
android:height setHeight(int) Makes the TextView be exactly this many pixels tall. 
android:hint setHint(int) Hint text to display when the text is empty. 
android:lines setLines(int) Makes the TextView be exactly this many lines tall. 
android:password setTransformationMethod(TransformationMethod) Whether the characters of the field are displayed as password dots instead of themselves. 
android:text setText(CharSequence) Text to display. 
android:textSize setTextSize(int, float) Size of the text. 
android:textStyle setTypeface(Typeface) Style (bold, italic, bolditalic) for the text. 
android:width setWidth(int) Makes the TextView be exactly this many pixels wide. 

 

Note: attributes and methods are common for TextView, Edit Text and Button

Events

Void OnTextChanged (CharSequence text, int start, int lengthBefore, int lengthAfter)
This method is called when the text is changed, in case any subclasses would like to know.


Boolean onGenericMotionEvent(MotionEvent event) 
Implement this method to handle generic motion event
 
setOnClickListerner(OnClickListener) 
Event occurs after clicking on button.