Search this blog

Showing posts with label Android Tutorial. Show all posts
Showing posts with label Android Tutorial. Show all posts

Handling animation life lycle events android

Now that you are happy with your animations, you just need to make
QuizSplashActivity transition to QuizMenuActivity when the animations
are complete. To do this, you create a new Intent control to launch the
QuizMenuActivity class and call the startActivity() method. You should also
call the finish() method of QuizSplashActivity because you do not want to keep
this activity on the stack (that is, you do not want the Back button to return to this
screen).

Of your animations, the fade_in2 animation takes the longest, at 5 seconds total.
This animation is therefore the one you want to trigger your transition upon. You do so by creating an AnimationListener object, which has callbacks for the animation life cycle events: start, end, and repeat. In this case, only the onAnimationEnd() method has an interesting implementation. Here is the code to create the AnimationListener and implement the onAnimationEnd() callback:
 
Animation fade2 = AnimationUtils.loadAnimation(this, R.anim.fade_in2);
fade2.setAnimationListener(new AnimationListener() {
public void onAnimationEnd(Animation animation) {
startActivity(new Intent(QuizSplashActivity.this,
QuizMenuActivity.class));
QuizSplashActivity.this.finish();
}
});

Now if you run the Been There, Done That! application again, either on the emulator or on the handset, you see some nice animation on the splash screen. The user then transitions smoothly to the main menu screen, which is the next screen on your to-do list.
READ MORE » Handling animation life lycle events android

How to animate all views in a Layout android


In addition to applying animations to individual View controls, you can also apply
them to each child View control within a Layout (such as TableLayout and each
TableRow), using LayoutAnimationController.
To animate View controls in this fashion, you must load the animation, create
LayoutAnimationController, configure it as necessary, and then call the layout’s
setLayoutAnimation() method. For example, the following code loads the custom_anim animation, creates a LayoutAnimationController, and then applies it to each TableRow in the TableLayout control:
 
Animation spinin = AnimationUtils.loadAnimation(this, R.anim.custom_anim);
LayoutAnimationController controller =new LayoutAnimationController(spinin);
TableLayout table = (TableLayout) findViewById(R.id.TableLayout01);
for (int i = 0; i < table.getChildCount(); i++)
{
TableRow row = (TableRow) table.getChildAt(i);
row.setLayoutAnimation(controller);
}
There is no need to call any startAnimation() method in this case because
LayoutAnimationController handles that for you. Using this method, the animation is applied to each child view, but each starts at a different time. (The default is 50% of the duration of the animation—which, in this case, would be 1 second.) This gives you the nice effect of each ImageView spinning into existence in a cascading fashion.
Stopping LayoutAnimationController animations is no different from stopping
individual animations: You simply use the clearAnimation() method. The additional lines to do this in the existing onPause() method are shown here:
TableLayout table = (TableLayout) findViewById(R.id.TableLayout01);
for (int i = 0; i < table.getChildCount(); i++) {
TableRow row = (TableRow) table.getChildAt(i);
row.clearAnimation();
}
READ MORE » How to animate all views in a Layout android

How to animate Specific Views in android

Animations must be applied and managed programmatically. Remember, costly
operations, such as animations, should be stopped if the application is paused for
some reason. The animation can resume when the application comes back into theforeground.
Let’s start with a simplest case: applying the fade_in animation to your title
TextView control, called TextViewTopTitle. All you need to do is retrieve an
instance of your TextView control in the onCreate() method of the
QuizSplashActivity class, load the animation resource into an Animation object,
and call the startAnimation() method of the TextView control:
TextView logo1 = (TextView) findViewById(R.id.TextViewTopTitle);
Animation fade1 = AnimationUtils.loadAnimation(this, R.anim.fade_in);
logo1.startAnimation(fade1);

When an animation must be stopped—for instance, in the onPause() method of the activity—you simply call the clearAnimation() method. For instance, the following
onPause() method demonstrates this for the corner logos:
@Override
protected void onPause() {
super.onPause();
// Stop the animation
TextView logo1 = (TextView) findViewById(R.id.TextViewTopTitle);
logo1.clearAnimation();
TextView logo2 = (TextView) findViewById(R.id.TextViewBottomTitle);
logo2.clearAnimation();
// ... stop other animations
}

READ MORE » How to animate Specific Views in android

How to add animation resources in android


For your splash screen, you need to create three custom animations in XML and
save them to the /res/anim resource directory: fade_in.xml, fade_in2.xml, and
custom_anim.xml.
The first animation, fade_in.xml, simply fades its target from an alpha value of 0
(transparent) to an alpha value of 1 (opaque) over the course of 2500 milliseconds, or 2.5 seconds. There is no built-in animation editor in Eclipse. The XML for the fade_in.xml animation looks like this:

<?xml version=”1.0” encoding=”utf-8” ?>
<set
xmlns:android=”http://schemas.android.com/apk/res/android”
android:shareInterpolator=”false”>
<alpha
android:fromAlpha=”0.0”
android:toAlpha=”1.0”
android:duration=”2500”>
</alpha>
</set>

You can apply this animation to the top TextView control with your title text.
Next, you create the fade_in2.xml animation. This animation does exactly the
same thing as the fade_in animation, except that you set the startOffset attribute
to 2500 milliseconds. This means that this animation will actually take 5 seconds
total: It waits 2.5 seconds and then fades in for 2.5 seconds. Because 5 seconds
is long enough to display the splash screen, you should plan to listen for fade_in2
to complete and then transition to the main menu screen.
Finally, you need some fun animation sequence for the TableLayout graphics. In
this case, your animation set contains multiple, simultaneous operations: a rotation, some scaling, and an alpha transition. As a result, the target View spins into existence.

The custom_anim.xml file looks like this:

<?xml version=”1.0” encoding=”utf-8” ?>
<set
xmlns:android=”http://schemas.android.com/apk/res/android”
android:shareInterpolator=”false”>
<rotate
android:fromDegrees=”0”
android:toDegrees=”360”
android:pivotX=”50%”
android:pivotY=”50%”
android:duration=”2000” />
<alpha
android:fromAlpha=”0.0”
android:toAlpha=”1.0”
android:duration=”2000”>
</alpha>
<scale
android:pivotX=”50%”
android:pivotY=”50%”
android:fromXScale=”.1”
android:fromYScale=”.1”
android:toXScale=”1.0”
android:toYScale=”1.0”
android:duration=”2000” />
</set>

As you can see, the rotation operation takes 2 seconds to rotate from 0 to
360 degrees, pivoting around the center of the view. The alpha operation should
look familiar; it simply fades in over the same 2-second period. Finally, the scale
operation scales from 10% to 100% over the same 2-second period. This entire animation takes 2 seconds to complete.
After you have saved all three of your animation files, you can begin to apply the
animations to specific views.


READ MORE » How to add animation resources in android

How to work with animation in android

One great way to add zing to your splash screen would be to add some animation.The Android platform supports four types of graphics animation:

Animated GIF images—Animated GIFs are self-contained graphics files with
multiple frames.

Frame-by-frame animation—The Android SDK provides a similar mechanism
for frame-by-frame animation in which the developer supplies the individual graphic frames and transitions between them (see the AnimationDrawable class).

Tweened animation—Tweened animation is a simple and flexible method of
defining specific animation operations that can then be applied to any view
or layout.

OpenGL ES—Android’s OpenGL ES API provides advanced three-dimensional
drawing, animation, lighting, and texturing capabilities.
 
For your application, the tweened animation makes the most sense. Android provides tweening support for alpha (transparency), rotation, scaling, and translating (moving) animations. You can create sets of animation operations do be done simultaneously, in a timed sequence, and after a delay. Thus, tweened animation is a perfect choice for your splash screen.With tweened animation, you create an animation sequence, either programmatically or by creating animation resources in the /res/anim directory. Each animation sequence needs its own XML file, but the animation may be applied to any number of View controls.
READ MORE » How to work with animation in android

How to design Layouts Using the Layout Resource Editor

You can design and preview layouts in Eclipse by using the layout resource editor
as shown in the below figure. If you click on the project file /res/layout/main.xml, you see a Layout tab, which shows you the preview of the layout. You can add and remove layout controls by using the Outline tab. You can set individual properties and attributes by using the Properties tab.

Like most other user interface designers, the layout resource editor works well for
basic layout design. However, the layout resource editor does not fully support all
View controls. For some of the more complex user interface controls, you might be
forced to edit the XML by hand. You might also lose the ability to preview your layout if you add any of these controls to your layout. In such a case, you can still view your layout by running your application in the emulator or on a handset.
Displaying an application correctly on a handset, rather than the Eclipse layout editor, should be a developer’s primary objective.


READ MORE » How to design Layouts Using the Layout Resource Editor

Information of android menifest file

The Android manifest file, named AndroidManifest.xml, is an XML file that must be included at the top level of any Android project. The Android system uses the information in this file to do the following:

  •  Install and upgrade the application package
  •  Display application details to users
  •  Launch application activities
  • Manage application permissions
     Handle a number of other advanced application configurations, including acting
    as a service provider or content provider.

You can edit the Android manifest file by using the Eclipse manifest file resource
editor or by manually editing the XML.
The Eclipse manifest file resource editor organizes the manifest information into
categories presented on five tabs:
  •  Manifest
  •  Application
  •  Permissions
  •  Instrumentation
  •  AndroidManifest.xml


READ MORE » Information of android menifest file

Working with layouts in android

Most Android application user interfaces are defined using specially formatted XML
files called layouts. Layout resource files are included in the /res/layout directory.
You compile layout files into your application as you would any other resources.

Here is an example of a layout resource 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” />
</LinearLayout>
You might recognize this layout: It is the default layout, called main.xml, created
with any new Android application. This layout file describes the user interface of the only activity within the application. It contains a LinearLayout control that is used as a container for all other user interface controls—in this case, a single TextView control. The main.xml layout file also references another resource: the string resource called @string/hello, which is defined in the strings.xml resource file.
There are two ways to format layout resources. The simplest way is to use the layout resource editor in Eclipse to design and preview layout files. You can also edit the XML layout files directly.


READ MORE » Working with layouts in android

How to access image resources programatically android

Images resources are encapsulated in the class BitmapDrawable. To access a graphic resource file called /res/drawable/logo.png, you would use the getDrawable() method, as follows:

BitmapDrawable logoBitmap =
(BitmapDrawable)getResources().getDrawable(R.drawable.logo);

Most of the time, however, you don’t need to load a graphic directly. Instead, you
can use the resource identifier as an attribute on a control such as an ImageView
control. The following code, for example, sets and loads the logo.png graphic into
an ImageView control named LogoImageView, which must be defined within the
layout:

ImageView logoView = (ImageView)findViewById(R.id.LogoImageView);
logoView.setImageResource(R.drawable.logo);
READ MORE » How to access image resources programatically android

Image formats supported in anroid


Supported images format their description and required extension is given below

Supported Image  Format                Description                   Required Extension

Portable Network Graphics              Preferred format                    .png

Nine-Patch Stretchable Images         Preferred format                   .9.png

Joint Photographic Experts Group    Acceptable format                   .jpg

Graphics Interchange Format               Discouraged but                   .gif
READ MORE » Image formats supported in anroid

How to work with Dimensions in android

To specify the size of a user interface control such as a Button or TextView control,you need to specify different kinds of dimensions. You tag dimension resources with the <dimen> tag and store them in the resource file /res/values/dimens.xml. This XML resource file is not created by default and must be created manually.

Here is an example of a dimension resource file:
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
<dimen name=”thumbDim”>100px</dimen>
</resources>
Each dimension resource value must end with a unit of measurement. Given below is the  list that shows the dimension units that Android supports.


Type of Measurement        Description                           Unit String
Pixels                                 Actual screen pixels                     px
Inches                                Physical measurement                 in
Millimeters                          Physical measurement                 mm
Points                                Common font measurement          pt
Density-independent pixels  Pixels relative to 160dpi                dp
Scale-independent pixels     Best for scalable font display         sp









READ MORE » How to work with Dimensions in android

Working with color in android

You can apply color resources to screen controls. You tag color resources with the
<color> tag and store them in the file /res/values/colors.xml. This XML
resource file is not created by default and must be created manually.



Here is an example of a color resource file:
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
<color name=”background_color”>#006400</color>
<color name=”app_text_color”>#FFE4C4</color>
</resources>
The Android system supports 12-bit and 24-bit colors in RGB format. Given below is the list that how many color formats that the Android platform supports.


Color Formats Supported in Android

Format                  Description                         Example
#RGB                     12-bit color                       #00F (blue)
#ARGB                 12-bit color with alpha         #800F (blue, alpha 50%)
#RRGGBB             24-bit color                        #FF00FF (magenta)
#AARRGGBB        24-bit color with alpha         # 80FF00FF (magenta, alpha 50%)

The following code retrieves a color resource named app_text_color using the
getColor() method:
int textColor = getResources().getColor(R.color.app_text_color);










READ MORE » Working with color in android

How to log android application information

Android provides a useful logging utility class called android.util.Log. Logging
messages are categorized by severity (and verbosity), with errors being the most
severe. Below see some commonly used logging methods of the Log class.

Method               Purpose

Log.e()                 Logs errors
Log.w()                Logs warnings
Log.i()                  Logs informational messages
Log.d()                 Logs debug messages
Log.v()                 Logs verbose messages


The first parameter of each Log method is a string called a tag. One common
Android programming practice is to define a global static string to represent the
overall application or the specific activity within the application such that log filters
can be created to limit the log output to specific data.
For example, you could define a string called TAG, as follows:
private static final String TAG = “MyApp”;
Now anytime you use a Log method, you supply this tag. An informational logging
message might look like this:
Log.i(TAG, “In onCreate() callback method”);
READ MORE » How to log android application information

How to use dialogue methods of activity class

Methods and their purpose

(1)Activity.showDialog()      
Shows a dialog, creating it if necessary.
 
(2)Activity.onCreateDialog()
Is a callback when a dialog is being created for the first time and added to the activity dialog pool.
 
(3)Activity.onPrepareDialog()
Is a callback for updating a dialog on-the-fly.Dialogs are created once and can be used many times by an activity. This callback enables the dialog to be updated just before it is shown for each showDialog() call.
 
(4)Activity.dismissDialog()        
Dismisses a dialog and returns to the activity. The dialog is still available to be used again by calling showDialog() again.
 
(5)Activity.removeDialog()  
Removes the dialog completely from the activity dialog pool.

Activity classes can include more than one dialog, and each dialog can be created
and then used multiple times.

You can also create an entirely custom dialog by designing an XML layout file and
using the Dialog.setContentView() method. To retrieve controls from the dialog
layout, you simply use the Dialog.findViewById() method.
READ MORE » How to use dialogue methods of activity class

How to provide input to android emulator

As a developer, you can adopt any one of the below way to provide input to the emulator:

. Use your computer mouse to click, scroll, and drag items (for example, side
volume controls) onscreen as well as on the emulator skin.
. Use your computer keyboard to input text into controls.
. Use your mouse to simulate individual finger presses on the soft keyboard or
physical emulator keyboard.
. Use a number of emulator keyboard commands to control specific emulator
states.
READ MORE » How to provide input to android emulator

How to use Intents to launch other applications

Initially, an application may only be launching activity classes defined within its own package. However, with the appropriate permissions, applications may also launch external activity classes in other applications.
There are well-defined intent actions for many common user tasks. For example, you can create intent actions to initiate applications such as the following:

. Launching the built-in web browser and supplying a URL address
. Launching the web browser and supplying a search string
. Launching the built-in Dialer application and supplying a phone number
. Launching the built-in Maps application and supplying a location
. Launching Google Street View and supplying a location
. Launching the built-in Camera application in still or video mode
. Launching a ringtone picker
. Recording a ሶዑንድ

Here is an example of how to create a simple intent with a predefined action(ACTION_VIEW) to launch the web browser with a specific URL:
Uri address = Uri.parse(“http://www.google.com”);
Intent surf = new Intent(Intent.ACTION_VIEW, address);
startActivity(surf);
This example shows an intent that has been created with an action and some data.The action, in this case, is to view something. The data is a uniform resource identifier (URI), which identifies the location of the resource to view.
For this example, the browser’s activity then starts and comes into foreground, causing the original calling activity to pause in the background. When the user finishes with the browser and clicks the Back button, the original activity resumes.
Applications may also create their own intent types and allow other applications to call them, allowing for tightly integrated application suites.

READ MORE » How to use Intents to launch other applications

How to pass Information with Intents

We can use Intents to pass data between activities.We can use an intent in this way by including additional data, called extras, within the intent.To package extra pieces of data along with an intent, you use the putExtra() method with the appropriate type of object you want to include. The Android programming
convention forintent extras is to name each one with the package prefix( for example, com.android. johnson.NameOfExtra).
For example, the following intent includes an extra piece of information, the current game level, which is an integer:

Intent intent = new Intent(getApplicationContext(), HelpActivity.class);
intent.putExtra(“com.android.johnson.LEVEL”, 23);
startActivity(intent);
When the HelpActivity class launches, the getIntent() method can be used to retrieve the intent. Then the extra information can be extracted using the appropriate methods. Here’s an example:

Intent callingIntent = getIntent();
int helpLevel = callingIntent.getIntExtra(“com.android.johnson.LEVEL”, 1);
This little piece of information could be used to give special Help hints, based on the level.For the parent activity that launched a subactivity using the startActivityForResult() method, the result will be passed in as a parameter to the onActivityResult() method with an Intent parameter. The intent data can then be extracted and used by the parent activity.
READ MORE » How to pass Information with Intents

How to launch Activities in Android



There are a number of ways to launch an activity, these are as under:


(1) Designating a launch activity in the manifest file
(2) Launching an activity using the application context
(3) Launching a child activity from a parent activity for a result
READ MORE » How to launch Activities in Android

How to Access Other Application Functionality by using Contexts


In Android with the help of application context you can do alot , an application context allows you to the following



 Launch Activity instances
 Retrieve assets packaged with the application
 Request a system-level service provider (for example, location service)
 Manage private application files, directories, and databases
 Inspect and enforce application permissions
READ MORE » How to Access Other Application Functionality by using Contexts

How to access Application Preferences in Android



Android provides you to retrieve shared application preferences by using the getSharedPreferences() method of the application context. You can use the SharedPreferences class to save simple application data, such as configuration settings.

You can give each SharedPreferences object a name, allowing you can organize preferences into categories or store preferences all together in one large set.


For example, you might want to keep track of each user’s name and some simple game state information, such as whether the user has credits left to play. The given below code creates a set of shared preferences called gampre and saves a few such preferences:

SharedPreferences settings = getSharedPreferences(“gampre”, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putString(“UserName”, “Spunky”);
prefEditor.putBoolean(“HasCredits”, true);
prefEditor.commit();

Now to retrieve preference settings, you simply retrieve SharedPreferences and read the desired values back out:

SharedPreferences settings = getSharedPreferences(“gampre”, MODE_PRIVATE);
String userName = settings.getString(“UserName”, “Chippy Jr. (Default)”);


READ MORE » How to access Application Preferences in Android