Search This Blog

Monday, 12 March 2012

Chapter 7:Toast


Toast

A toast notification is a message that pops up on the surface of the window. It only fills the amount of space required for the message and the user's current activity remains visible and interactive. The notification automatically fades in and out, and does not accept interaction events.
The screenshot below shows an example toast notification from the Alarm application. Once an alarm is turned on, a toast is displayed to assure you that the alarm was set.

A toast can be created and displayed from an Activity or Service. If you create a toast notification from a Service, it appears in front of the Activity currently in focus.
If user response to the notification is required, consider using a Status Bar Notification.

The Basics

First, instantiate a Toast object with one of the makeText() methods. This method takes three parameters: the application Context, the text message, and the duration for the toast. It returns a properly initialized Toast object. You can display the toast notification with show(), as shown in the following example:
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
This example demonstrates everything you need for most toast notifications. You should rarely need anything else. You may, however, want to position the toast differently or even use your own layout instead of a simple text message. The following sections describe how you can do these things.
You can also chain your methods and avoid holding on to the Toast object, like this:
Toast.makeText(context, text, duration).show();

Positioning your Toast

A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.
For example, if you decide that the toast should appear in the top-left corner, you can set the gravity like this:
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
If you want to nudge the position to the right, increase the value of the second parameter. To nudge it down, increase the value of the last parameter.

Creating a Custom Toast View

If a simple text message isn't enough, you can create a customized layout for your toast notification. To create a custom layout, define a View layout, in XML or in your application code, and pass the root View object to the setView(View) method.
For example, you can create the layout for the toast visible in the screenshot to the right with the following XML (saved as toast_layout.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/toast_layout_root"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp"
              android:background="#DAAA"
              >
    <ImageView android:id="@+id/image"
               android:layout_width="wrap_content"
               android:layout_height="fill_parent"
               android:layout_marginRight="10dp"
               />
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:textColor="#FFF"
              />
</LinearLayout>
Notice that the ID of the LinearLayout element is "toast_layout". You must use this ID to inflate the layout from the XML, as shown here:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,
                               (ViewGroup) findViewById(R.id.toast_layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello! This is a custom toast!");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
First, retrieve the LayoutInflater with getLayoutInflater() (or getSystemService()), and then inflate the layout from XML using inflate(int, ViewGroup). The first parameter is the layout resource ID and the second is the root View. You can use this inflated layout to find more View objects in the layout, so now capture and define the content for the ImageView and TextView elements. Finally, create a new Toast with Toast(Context) and set some properties of the toast, such as the gravity and duration. Then call setView(View) and pass it the inflated layout. You can now display the toast with your custom layout by calling show().






Example program
MainActivity
package com.ipsr;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;



public class MainActivity extends Activity
{
private static final int ALERT_DIALOG = 1;



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

( (Button) findViewById( R.id.button1 ) )
.setOnClickListener( new OnClickListener()
{
@Override
public void onClick( View v )
{
showDialog( ALERT_DIALOG );
}
}
);
}



@Override
protected Dialog onCreateDialog( int id )
{
Dialog dialog = null;
if ( id == ALERT_DIALOG )
{
ContextThemeWrapper ctw = new ContextThemeWrapper( this, R.style.MyTheme );
AlertDialog.Builder builder= new AlertDialog.Builder( ctw );
builder.setMessage( "Hello World" )
.setTitle( "Alert Dialog" )
.setIcon( android.R.drawable.ic_dialog_alert )
.setCancelable( false )
.setPositiveButton( "Close",
new DialogInterface.OnClickListener()
{
@Override
public void onClick( DialogInterface dialog, int which )
{
dialog.dismiss();
}
}
);
dialog = builder.create();
}
if ( dialog == null )
{
dialog = super.onCreateDialog( id );
}
return dialog;
}
}



AlerdialogActivity



package com.ipsr;

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

public class AlerdialogActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}


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" android:gravity="center_horizontal">
<Button android:text="Click Me!" android:id="@+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>






DATE

Public Constructors

public Date ()

Since: API Level 1
Initializes this Date instance to the current time.

public Date (int year, int month, int day)

Since: API Level 1
This constructor is deprecated.
use GregorianCalendar(int, int, int)
Constructs a new Date initialized to midnight in the default TimeZone on the specified date.
Parameters
year
the year, 0 is 1900.
month
the month, 0 - 11.
day
the day of the month, 1 - 31.

public Date (int year, int month, int day, int hour, int minute)

Since: API Level 1
This constructor is deprecated.
use GregorianCalendar(int, int, int, int, int)
Constructs a new Date initialized to the specified date and time in the default TimeZone.
Parameters
year
the year, 0 is 1900.
month
the month, 0 - 11.
day
the day of the month, 1 - 31.
hour
the hour of day, 0 - 23.
minute
the minute of the hour, 0 - 59.

public Date (int year, int month, int day, int hour, int minute, int second)

Since: API Level 1
This constructor is deprecated.
use GregorianCalendar(int, int, int, int, int, int)
Constructs a new Date initialized to the specified date and time in the default TimeZone.
Parameters
year
the year, 0 is 1900.
month
the month, 0 - 11.
day
the day of the month, 1 - 31.
hour
the hour of day, 0 - 23.
minute
the minute of the hour, 0 - 59.
second
the second of the minute, 0 - 59.

public Date (long milliseconds)

Since: API Level 1
Initializes this Date instance using the specified millisecond value. The value is the number of milliseconds since Jan. 1, 1970 GMT.
Parameters
milliseconds
the number of milliseconds since Jan. 1, 1970 GMT.

public Date (String string)

Since: API Level 1
This constructor is deprecated.
use DateFormat
Constructs a new Date initialized to the date and time parsed from the specified String.
Parameters
string
the String to parse.

Public Methods

public static long UTC (int year, int month, int day, int hour, int minute, int second)

Since: API Level 1
This method is deprecated.
use: Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); cal.set(year + 1900, month, day, hour, minute, second); cal.getTime().getTime();
Returns the millisecond value of the specified date and time in GMT.
Parameters
year
the year, 0 is 1900.
month
the month, 0 - 11.
day
the day of the month, 1 - 31.
hour
the hour of day, 0 - 23.
minute
the minute of the hour, 0 - 59.
second
the second of the minute, 0 - 59.
Returns
  • the date and time in GMT in milliseconds.

public boolean after (Date date)

Since: API Level 1
Returns if this Date is after the specified Date.
Parameters
date
a Date instance to compare.
Returns
  • true if this Date is after the specified Date, false otherwise.

public boolean before (Date date)

Since: API Level 1
Returns if this Date is before the specified Date.
Parameters
date
a Date instance to compare.
Returns
  • true if this Date is before the specified Date, false otherwise.

public Object clone ()

Since: API Level 1
Returns a new Date with the same millisecond value as this Date.
Returns
  • a shallow copy of this Date.
See Also

public int compareTo (Date date)

Since: API Level 1
Compare the receiver to the specified Date to determine the relative ordering.
Parameters
date
a Date to compare against.
Returns
  • an int < 0 if this Date is less than the specified Date, 0 if they are equal, and an int > 0 if this Date is greater.

public boolean equals (Object object)

Since: API Level 1
Compares the specified object to this Date and returns if they are equal. To be equal, the object must be an instance of Date and have the same millisecond value.
Parameters
object
the object to compare with this object.
Returns
  • true if the specified object is equal to this Date, false otherwise.
See Also

public int getDate ()

Since: API Level 1
This method is deprecated.
use Calendar.get(Calendar.DATE)
Returns the gregorian calendar day of the month for this Date object.
Returns
  • the day of the month.

public int getDay ()

Since: API Level 1
This method is deprecated.
use Calendar.get(Calendar.DAY_OF_WEEK)
Returns the gregorian calendar day of the week for this Date object.
Returns
  • the day of the week.

public int getHours ()

Since: API Level 1
This method is deprecated.
use Calendar.get(Calendar.HOUR_OF_DAY)
Returns the gregorian calendar hour of the day for this Date object.
Returns
  • the hour of the day.

public int getMinutes ()

Since: API Level 1
This method is deprecated.
use Calendar.get(Calendar.MINUTE)
Returns the gregorian calendar minute of the hour for this Date object.
Returns
  • the minutes.

public int getMonth ()

Since: API Level 1
This method is deprecated.
use Calendar.get(Calendar.MONTH)
Returns the gregorian calendar month for this Date object.
Returns
  • the month.

public int getSeconds ()

Since: API Level 1
This method is deprecated.
use Calendar.get(Calendar.SECOND)
Returns the gregorian calendar second of the minute for this Date object.
Returns
  • the seconds.

public long getTime ()

Since: API Level 1
Returns this Date as a millisecond value. The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.
Returns
  • the number of milliseconds since Jan. 1, 1970, midnight GMT.

public int getTimezoneOffset ()

Since: API Level 1
This method is deprecated.
use (Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)) / 60000
Returns the timezone offset in minutes of the default TimeZone.
Returns
  • the timezone offset in minutes of the default TimeZone.

public int getYear ()

Since: API Level 1
This method is deprecated.
use Calendar.get(Calendar.YEAR) - 1900
Returns the gregorian calendar year since 1900 for this Date object.
Returns
  • the year - 1900.

public int hashCode ()

Since: API Level 1
Returns an integer hash code for the receiver. Objects which are equal return the same value for this method.
Returns
  • this Date's hash.
See Also

public static long parse (String string)

Since: API Level 1
This method is deprecated.
use DateFormat
Returns the millisecond value of the date and time parsed from the specified String. Many date/time formats are recognized, including IETF standard syntax, i.e. Tue, 22 Jun 1999 12:16:00 GMT-0500
Parameters
string
the String to parse.
Returns
  • the millisecond value parsed from the String.

public void setDate (int day)

Since: API Level 1
This method is deprecated.
use Calendar.set(Calendar.DATE, day)
Sets the gregorian calendar day of the month for this Date object.
Parameters
day
the day of the month.

public void setHours (int hour)

Since: API Level 1
This method is deprecated.
use Calendar.set(Calendar.HOUR_OF_DAY, hour)
Sets the gregorian calendar hour of the day for this Date object.
Parameters
hour
the hour of the day.

public void setMinutes (int minute)

Since: API Level 1
This method is deprecated.
use Calendar.set(Calendar.MINUTE, minute)
Sets the gregorian calendar minute of the hour for this Date object.
Parameters
minute
the minutes.

public void setMonth (int month)

Since: API Level 1
This method is deprecated.
use Calendar.set(Calendar.MONTH, month)
Sets the gregorian calendar month for this Date object.
Parameters
month
the month.

public void setSeconds (int second)

Since: API Level 1
This method is deprecated.
use Calendar.set(Calendar.SECOND, second)
Sets the gregorian calendar second of the minute for this Date object.
Parameters
second
the seconds.

public void setTime (long milliseconds)

Since: API Level 1
Sets this Date to the specified millisecond value. The value is the number of milliseconds since Jan. 1, 1970 GMT.
Parameters
milliseconds
the number of milliseconds since Jan. 1, 1970 GMT.

public void setYear (int year)

Since: API Level 1
This method is deprecated.
use Calendar.set(Calendar.YEAR, year + 1900)
Sets the gregorian calendar year since 1900 for this Date object.
Parameters
year
the year since 1900.

public String toGMTString ()

Since: API Level 1
This method is deprecated.
use DateFormat
Returns the string representation of this Date in GMT in the format "22 Jun 1999 13:02:00 GMT".

public String toLocaleString ()

Since: API Level 1
This method is deprecated.
use DateFormat
Returns the string representation of this Date for the default Locale.

public String toString ()

Since: API Level 1
Returns a string representation of this Date. The formatting is equivalent to using a SimpleDateFormat with the format string "EEE MMM dd HH:mm:ss zzz yyyy", which looks something like "Tue Jun 22 13:07:00 PDT 1999". The current default time zone and locale are used. If you need control over the time zone or locale, use SimpleDateFormat instead.
Returns
  • a printable representation of this object

TIME

Constants

public static final int EPOCH_JULIAN_DAY

Since: API Level 3
The Julian day of the epoch, that is, January 1, 1970 on the Gregorian calendar.
Constant Value: 2440588 (0x00253d8c)

public static final int FRIDAY

Since: API Level 3
Constant Value: 5 (0x00000005)

public static final int HOUR

Since: API Level 3
Constant Value: 3 (0x00000003)

public static final int MINUTE

Since: API Level 3
Constant Value: 2 (0x00000002)

public static final int MONDAY

Since: API Level 3
Constant Value: 1 (0x00000001)

public static final int MONDAY_BEFORE_JULIAN_EPOCH

Since: API Level 11
The Julian day of the Monday in the week of the epoch, December 29, 1969 on the Gregorian calendar.
Constant Value: 2440585 (0x00253d89)

public static final int MONTH

Since: API Level 3
Constant Value: 5 (0x00000005)

public static final int MONTH_DAY

Since: API Level 3
Constant Value: 4 (0x00000004)

public static final int SATURDAY

Since: API Level 3
Constant Value: 6 (0x00000006)

public static final int SECOND

Since: API Level 3
Constant Value: 1 (0x00000001)

public static final int SUNDAY

Since: API Level 3
Constant Value: 0 (0x00000000)

public static final int THURSDAY

Since: API Level 3
Constant Value: 4 (0x00000004)

public static final String TIMEZONE_UTC

Since: API Level 3
Constant Value: "UTC"

public static final int TUESDAY

Since: API Level 3
Constant Value: 2 (0x00000002)

public static final int WEDNESDAY

Since: API Level 3
Constant Value: 3 (0x00000003)

public static final int WEEK_DAY

Since: API Level 3
Constant Value: 7 (0x00000007)

public static final int WEEK_NUM

Since: API Level 3
Constant Value: 9 (0x00000009)

public static final int YEAR

Since: API Level 3
Constant Value: 6 (0x00000006)

public static final int YEAR_DAY

Since: API Level 3
Constant Value: 8 (0x00000008)

Fields

public boolean allDay

Since: API Level 3
True if this is an allDay event. The hour, minute, second fields are all zero, and the date is displayed the same in all time zones.

public long gmtoff

Since: API Level 3
Offset from UTC (in seconds).

public int hour

Since: API Level 3
Hour of day [0-23]

public int isDst

Since: API Level 3
This time is in daylight savings time. One of:
  • positive - in dst
  • 0 - not in dst
  • negative - unknown

public int minute

Since: API Level 3
Minute [0-59]

public int month

Since: API Level 3
Month [0-11]

public int monthDay

Since: API Level 3
Day of month [1-31]

public int second

Since: API Level 3
Seconds [0-61] (2 leap seconds allowed)

public String timezone

Since: API Level 3
The timezone for this Time. Should not be null.

public int weekDay

Since: API Level 3
Day of week [0-6]

public int year

Since: API Level 3
Year. For example, 1970.

public int yearDay

Since: API Level 3
Day of year [0-365]

Public Constructors

public Time (String timezone)

Since: API Level 3
Construct a Time object in the timezone named by the string argument "timezone". The time is initialized to Jan 1, 1970.
Parameters
timezone
string containing the timezone to use.
See Also

public Time ()

Since: API Level 3
Construct a Time object in the default timezone. The time is initialized to Jan 1, 1970.

public Time (Time other)

Since: API Level 3
A copy constructor. Construct a Time object by copying the given Time object. No normalization occurs.

Public Methods

public boolean after (Time that)

Since: API Level 3
Returns true if the time represented by this Time object occurs after the given time.
Parameters
that
a given Time object to compare against
Returns
  • true if this time is greater than the given time

public boolean before (Time that)

Since: API Level 3
Returns true if the time represented by this Time object occurs before the given time.
Parameters
that
a given Time object to compare against
Returns
  • true if this time is less than the given time

public void clear (String timezone)

Since: API Level 3
Clears all values, setting the timezone to the given timezone. Sets isDst to a negative value to mean "unknown".
Parameters
timezone
the timezone to use.

public static int compare (Time a, Time b)

Since: API Level 3
Compare two Time objects and return a negative number if a is less than b, a positive number if a is greater than b, or 0 if they are equal.
Parameters
a
first Time instance to compare
b
second Time instance to compare
Returns
  • a negative result if a is earlier, a positive result if a is earlier, or 0 if they are equal.
Throws
NullPointerException
if either argument is null
IllegalArgumentException
if allDay is true but hour, minute, and second are not 0.

public String format (String format)

Since: API Level 3
Print the current value given the format string provided. See man strftime for what means what. The final string must be less than 256 characters.
Parameters
format
a string containing the desired format.
Returns
  • a String containing the current time expressed in the current locale.

public String format2445 ()

Since: API Level 3
Format according to RFC 2445 DATETIME type.
The same as format("%Y%m%dT%H%M%S").

public String format3339 (boolean allDay)

Since: API Level 3
Return a string in the RFC 3339 format.
If allDay is true, expresses the time as Y-M-D
Otherwise, if the timezone is UTC, expresses the time as Y-M-D-T-H-M-S UTC
Otherwise the time is expressed the time as Y-M-D-T-H-M-S +- GMT
Returns
  • string in the RFC 3339 format.

public int getActualMaximum (int field)

Since: API Level 3
Return the maximum possible value for the given field given the value of the other fields. Requires that it be normalized for MONTH_DAY and YEAR_DAY.
Parameters
field
one of the constants for HOUR, MINUTE, SECOND, etc.
Returns
  • the maximum value for the field.

public static String getCurrentTimezone ()

Since: API Level 3
Returns the timezone string that is currently set for the device.

public static int getJulianDay (long millis, long gmtoff)

Since: API Level 3
Computes the Julian day number, given the UTC milliseconds and the offset (in seconds) from UTC. The Julian day for a given date will be the same for every timezone. For example, the Julian day for July 1, 2008 is 2454649. This is the same value no matter what timezone is being used. The Julian day is useful for testing if two events occur on the same day and for determining the relative time of an event from the present ("yesterday", "3 days ago", etc.).
Use toMillis(boolean) to get the milliseconds.
Parameters
millis
the time in UTC milliseconds
gmtoff
the offset from UTC in seconds
Returns
  • the Julian day

public static int getJulianMondayFromWeeksSinceEpoch (int week)

Since: API Level 11
Takes a number of weeks since the epoch and calculates the Julian day of the Monday for that week. This assumes that the week containing the EPOCH_JULIAN_DAY is considered week 0. It returns the Julian day for the Monday week weeks after the Monday of the week containing the epoch.
Parameters
week
Number of weeks since the epoch
Returns
  • The julian day for the Monday of the given week since the epoch

public int getWeekNumber ()

Since: API Level 3
Computes the week number according to ISO 8601. The current Time object must already be normalized because this method uses the yearDay and weekDay fields.
In IS0 8601, weeks start on Monday. The first week of the year (week 1) is defined by ISO 8601 as the first week with four or more of its days in the starting year. Or equivalently, the week containing January 4. Or equivalently, the week with the year's first Thursday in it.
The week number can be calculated by counting Thursdays. Week N contains the Nth Thursday of the year.
Returns
  • the ISO week number.

public static int getWeeksSinceEpochFromJulianDay (int julianDay, int firstDayOfWeek)

Since: API Level 11
Returns the week since EPOCH_JULIAN_DAY (Jan 1, 1970) adjusted for first day of week. This takes a julian day and the week start day and calculates which week since EPOCH_JULIAN_DAY that day occurs in, starting at 0. *Do not* use this to compute the ISO week number for the year.
Parameters
julianDay
The julian day to calculate the week number for
firstDayOfWeek
Which week day is the first day of the week, see SUNDAY
Returns
  • Weeks since the epoch

public static boolean isEpoch (Time time)

Since: API Level 3
Returns true if the day of the given time is the epoch on the Julian Calendar (January 1, 1970 on the Gregorian calendar).
Parameters
time
the time to test
Returns
  • true if epoch.

public long normalize (boolean ignoreDst)

Since: API Level 3
Ensures the values in each field are in range. For example if the current value of this calendar is March 32, normalize() will convert it to April 1. It also fills in weekDay, yearDay, isDst and gmtoff.
If "ignoreDst" is true, then this method sets the "isDst" field to -1 (the "unknown" value) before normalizing. It then computes the correct value for "isDst".
See toMillis(boolean) for more information about when to use true or false for "ignoreDst".
Returns
  • the UTC milliseconds since the epoch

public boolean parse (String s)

Since: API Level 3
Parses a date-time string in either the RFC 2445 format or an abbreviated format that does not include the "time" field. For example, all of the following strings are valid:
  • "20081013T160000Z"
  • "20081013T160000"
  • "20081013"
Returns whether or not the time is in UTC (ends with Z). If the string ends with "Z" then the timezone is set to UTC. If the date-time string included only a date and no time field, then the allDay field of this Time class is set to true and the hour, minute, and second fields are set to zero; otherwise (a time field was included in the date-time string) allDay is set to false. The fields weekDay, yearDay, and gmtoff are always set to zero, and the field isDst is set to -1 (unknown). To set those fields, call normalize(boolean) after parsing. To parse a date-time string and convert it to UTC milliseconds, do something like this:
   Time time = new Time();
   String date = "20081013T160000Z";
   time.parse(date);
   long millis = time.normalize(false);
 
Parameters
s
the string to parse
Returns
  • true if the resulting time value is in UTC time
Throws
TimeFormatException
if s cannot be parsed.

public boolean parse3339 (String s)

Since: API Level 3
Parse a time in RFC 3339 format. This method also parses simple dates (that is, strings that contain no time or time offset). For example, all of the following strings are valid:
  • "2008-10-13T16:00:00.000Z"
  • "2008-10-13T16:00:00.000+07:00"
  • "2008-10-13T16:00:00.000-07:00"
  • "2008-10-13"
If the string contains a time and time offset, then the time offset will be used to convert the time value to UTC.
If the given string contains just a date (with no time field), then the allDay field is set to true and the hour, minute, and second fields are set to zero.
Returns true if the resulting time value is in UTC time.
Parameters
s
the string to parse
Returns
  • true if the resulting time value is in UTC time
Throws
TimeFormatException
if s cannot be parsed.

public void set (int second, int minute, int hour, int monthDay, int month, int year)

Since: API Level 3
Sets the fields. Sets weekDay, yearDay and gmtoff to 0, and isDst to -1. Call normalize(boolean) if you need those.

public void set (int monthDay, int month, int year)

Since: API Level 3
Sets the date from the given fields. Also sets allDay to true. Sets weekDay, yearDay and gmtoff to 0, and isDst to -1. Call normalize(boolean) if you need those.
Parameters
monthDay
the day of the month (in the range [1,31])
month
the zero-based month number (in the range [0,11])
year
the year

public void set (Time that)

Since: API Level 3
Copy the value of that to this Time object. No normalization happens.

public void set (long millis)

Since: API Level 3
Sets the fields in this Time object given the UTC milliseconds. After this method returns, all the fields are normalized. This also sets the "isDst" field to the correct value.
Parameters
millis
the time in UTC milliseconds since the epoch.

public long setJulianDay (int julianDay)

Since: API Level 3
Sets the time from the given Julian day number, which must be based on the same timezone that is set in this Time object. The "gmtoff" field need not be initialized because the given Julian day may have a different GMT offset than whatever is currently stored in this Time object anyway. After this method returns all the fields will be normalized and the time will be set to 12am at the beginning of the given Julian day.
The only exception to this is if 12am does not exist for that day because of daylight saving time. For example, Cairo, Eqypt moves time ahead one hour at 12am on April 25, 2008 and there are a few other places that also change daylight saving time at 12am. In those cases, the time will be set to 1am.
Parameters
julianDay
the Julian day in the timezone for this Time object
Returns
  • the UTC milliseconds for the beginning of the Julian day

public void setToNow ()

Since: API Level 3
Sets the time of the given Time object to the current time.

public void switchTimezone (String timezone)

Since: API Level 3
Convert this time object so the time represented remains the same, but is instead located in a different timezone. This method automatically calls normalize() in some cases

public long toMillis (boolean ignoreDst)

Since: API Level 3
Converts this time to milliseconds. Suitable for interacting with the standard java libraries. The time is in UTC milliseconds since the epoch. This does an implicit normalization to compute the milliseconds but does not change any of the fields in this Time object. If you want to normalize the fields in this Time object and also get the milliseconds then use normalize(boolean).
If "ignoreDst" is false, then this method uses the current setting of the "isDst" field and will adjust the returned time if the "isDst" field is wrong for the given time. See the sample code below for an example of this.
If "ignoreDst" is true, then this method ignores the current setting of the "isDst" field in this Time object and will instead figure out the correct value of "isDst" (as best it can) from the fields in this Time object. The only case where this method cannot figure out the correct value of the "isDst" field is when the time is inherently ambiguous because it falls in the hour that is repeated when switching from Daylight-Saving Time to Standard Time.
Here is an example where toMillis(true) adjusts the time, assuming that DST changes at 2am on Sunday, Nov 4, 2007.
 Time time = new Time();
 time.set(4, 10, 2007);  // set the date to Nov 4, 2007, 12am
 time.normalize();       // this sets isDst = 1
 time.monthDay += 1;     // changes the date to Nov 5, 2007, 12am
 millis = time.toMillis(false);   // millis is Nov 4, 2007, 11pm
 millis = time.toMillis(true);    // millis is Nov 5, 2007, 12am
 
To avoid this problem, use toMillis(true) after adding or subtracting days or explicitly setting the "monthDay" field. On the other hand, if you are adding or subtracting hours or minutes, then you should use toMillis(false).
You should also use toMillis(false) if you want to read back the same milliseconds that you set with set(long) or set(Time) or after parsing a date string.

public String toString ()

Since: API Level 3
Return the current time in YYYYMMDDTHHMMSS format
Returns
  • a printable representation of this object.



Example program
DateTime



CalendarAdapter



package com.ipsr.datetime;



import java.util.ArrayList;
import java.util.Calendar;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;



import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;



public class CalendarAdapter extends BaseAdapter {
static final int FIRST_DAY_OF_WEEK =0; // Sunday = 0, Monday = 1


private Context mContext;



private java.util.Calendar month;
private Calendar selectedDate;
private ArrayList<String> items;

public CalendarAdapter(Context c, Calendar monthCalendar) {
month = monthCalendar;
selectedDate = (Calendar)monthCalendar.clone();
mContext = c;
month.set(Calendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<String>();
refreshDays();
}

public void setItems(ArrayList<String> items) {
this.items = items;
}




public int getCount() {
return days.length;
}



public Object getItem(int position) {
return null;
}



public long getItemId(int position) {
return 0;
}



// create a new view for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView dayView;
if (convertView == null) { // if it's not recycled, initialize some attributes
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.calendar_item, null);

}
dayView = (TextView)v.findViewById(R.id.date);

// disable empty days from the beginning
if(days[position].equals("")) {
dayView.setClickable(false);
dayView.setFocusable(false);
}
else {
// mark current day as focused
if(month.get(Calendar.YEAR)== selectedDate.get(Calendar.YEAR) && month.get(Calendar.MONTH)== selectedDate.get(Calendar.MONTH) && days[position].equals(""+selectedDate.get(Calendar.DAY_OF_MONTH))) {
v.setBackgroundResource(R.drawable.item_background_focused);
}
else {
v.setBackgroundResource(R.drawable.list_item_background);
}
}
dayView.setText(days[position]);

// create date string for comparison
String date = days[position];

if(date.length()==1) {
date = "0"+date;
}
String monthStr = ""+(month.get(Calendar.MONTH)+1);
if(monthStr.length()==1) {
monthStr = "0"+monthStr;
}

// show icon if date is not empty and it exists in the items array
ImageView iw = (ImageView)v.findViewById(R.id.date_icon);
if(date.length()>0 && items!=null && items.contains(date)) {
iw.setVisibility(View.VISIBLE);
}
else {
iw.setVisibility(View.INVISIBLE);
}
return v;
}

public void refreshDays()
{
// clear items
items.clear();

int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDay = (int)month.get(Calendar.DAY_OF_WEEK);

// figure size of the array
if(firstDay==1){
days = new String[lastDay+(FIRST_DAY_OF_WEEK*6)];
}
else {
days = new String[lastDay+firstDay-(FIRST_DAY_OF_WEEK+1)];
}

int j=FIRST_DAY_OF_WEEK;

// populate empty days before first real day
if(firstDay>1) {
for(j=0;j<firstDay-FIRST_DAY_OF_WEEK;j++) {
days[j] = "";
}
}
else {
for(j=0;j<FIRST_DAY_OF_WEEK*6;j++) {
days[j] = "";
}
j=FIRST_DAY_OF_WEEK*6+1; // sunday => 1, monday => 7
}

// populate days
int dayNumber = 1;
for(int i=j-1;i<days.length;i++) {
days[i] = ""+dayNumber;
dayNumber++;
}
}



// references to our items
public String[] days;
}



CalendarView



package com.ipsr.datetime;



import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;






import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;






public class CalendarView extends Activity {



public Calendar month;
public CalendarAdapter adapter;
public Handler handler;
public ArrayList<String> items; // container to store some random calendar items

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar);
month = Calendar.getInstance();
onNewIntent(getIntent());

items = new ArrayList<String>();
adapter = new CalendarAdapter(this, month);

GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(adapter);

handler = new Handler();
handler.post(calendarUpdater);

TextView title = (TextView) findViewById(R.id.title);
title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));

TextView previous = (TextView) findViewById(R.id.previous);
previous.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if(month.get(Calendar.MONTH)== month.getActualMinimum(Calendar.MONTH)) {
month.set((month.get(Calendar.YEAR)-1),month.getActualMaximum(Calendar.MONTH),1);
} else {
month.set(Calendar.MONTH,month.get(Calendar.MONTH)-1);
}
refreshCalendar();
}
});

TextView next = (TextView) findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if(month.get(Calendar.MONTH)== month.getActualMaximum(Calendar.MONTH)) {
month.set((month.get(Calendar.YEAR)+1),month.getActualMinimum(Calendar.MONTH),1);
} else {
month.set(Calendar.MONTH,month.get(Calendar.MONTH)+1);
}
refreshCalendar();

}
});

gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
TextView date = (TextView)v.findViewById(R.id.date);
if(date instanceof TextView && !date.getText().equals("")) {

Intent intent = new Intent();
String day = date.getText().toString();
if(day.length()==1) {
day = "0"+day;
}
// return chosen date as string format
intent.putExtra("date", android.text.format.DateFormat.format("yyyy-MM", month)+"-"+day);
setResult(RESULT_OK, intent);
finish();
}

}
});
}

public void refreshCalendar()
{
TextView title = (TextView) findViewById(R.id.title);

adapter.refreshDays();
adapter.notifyDataSetChanged();
handler.post(calendarUpdater); // generate some random calendar items

title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
}

public void onNewIntent(Intent intent) {
String date = intent.getStringExtra("date");
String[] dateArr = date.split("-"); // date format is yyyy-mm-dd
month.set(Integer.parseInt(dateArr[0]), Integer.parseInt(dateArr[1]), Integer.parseInt(dateArr[2]));
}

public Runnable calendarUpdater = new Runnable() {

@Override
public void run() {
items.clear();
// format random values. You can implement a dedicated class to provide real values
for(int i=0;i<31;i++) {
Random r = new Random();

if(r.nextInt(10)>6)
{
items.add(Integer.toString(i));
}
}



adapter.setItems(items);
adapter.notifyDataSetChanged();
}
};
}



CalendarViewSampleActivity
package com.ipsr.datetime;



import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Toast;



public class CalendarViewSampleActivity extends Activity {
/** Called when the activity is first created. */

static final int DATE_DIALOG_ID = 0;
static final int PICK_DATE_REQUEST = 1;



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

Button openButton = (Button)findViewById(R.id.openButton);

openButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
DatePicker dp = (DatePicker)findViewById(R.id.datePicker1);
Intent intent = new Intent(v.getContext(),CalendarView.class);

intent.putExtra("date", dp.getYear()+"-"+dp.getMonth()+"-"+dp.getDayOfMonth());
startActivityForResult(intent, PICK_DATE_REQUEST);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_DATE_REQUEST) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), data.getStringExtra("date"), Toast.LENGTH_SHORT).show();
String[] dateArr = data.getStringExtra("date").split("-");
DatePicker dp = (DatePicker)findViewById(R.id.datePicker1);
dp.updateDate(Integer.parseInt(dateArr[0]), Integer.parseInt(dateArr[1]), Integer.parseInt(dateArr[2]));
}
}
}

}





http://saigeethamn.blogspot.in/2010/05/date-and-time-picker-views-android.html

No comments:

Post a Comment