Animation image in Android

Here I will show you how to make an animation image in Android.

It is very easy to make a animation image in background.
The first thing you need is to create a image view in your layout.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".TheDeveloperWorldIsYours" >
    <ImageView android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/iv"/>

</RelativeLayout>

The most import line code is

final Handler handler = new Handler();
final Runnable r = new Runnable(){
      public void run(){};
}

a Handler, a Runnable and a run.

package com.thedeveloperworldisyours.animationimagen;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;

public class TheDeveloperWorldIsYours extends Activity {

	private static ImageView iv;

	final Handler handler = new Handler();
	Runnable r;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_the_developer_world_is_yours);

		iv = (ImageView) findViewById(R.id.iv);

		r = new Runnable()
		{
			int x = 1;
		    public void run()
		    {

		        switch(x) {
				 case 1:
					 iv.setImageResource(R.drawable.base1);
				     break;
				 case 2:
					 iv.setImageResource(R.drawable.base2);
				     break;
				 case 3:
					 iv.setImageResource(R.drawable.base3);
				     break;
				 case 4:
					 iv.setImageResource(R.drawable.base4);
				     break;
				 case 5:
					 iv.setImageResource(R.drawable.base5);
				     break;
				 case 6:
					 iv.setImageResource(R.drawable.base6);
				     break;
				 case 7:
					 iv.setImageResource(R.drawable.base7);
				     break;
				 case 8:
					 iv.setImageResource(R.drawable.base8);
				     break;
				 case 9:
					 iv.setImageResource(R.drawable.base9);
				     break;
				 default:
					 iv.setImageResource(R.drawable.base);
				     break;
				 }
		        if(x==9)
		        	x=1;
		        else
		        	x++;
		        handler.postDelayed(this, 1000);

		    }
		};

		handler.postDelayed(r, 1000);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		handler.removeCallbacks(r);
		super.onPause();
	}

}

Popup in Android

In android you can control the view in any away.
A way is with inflater

// Inflate the popup_layout.xml
            LinearLayout viewGroup = (LinearLayout) context
                            .findViewById(R.id.popupLinearLayout);
            LayoutInflater layoutInflater = (LayoutInflater) context
                            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View layout = layoutInflater.inflate(R.layout.activity_popup, viewGroup);

You can download this code: Download code

First step is animation. One for enter and other for exit.

res/anim/enter.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/decelerate_interpolator" >

    <scale
        android:duration="1000"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.0"
        android:toYScale="1.0" />

    <alpha
        android:duration="2000"
        android:fromAlpha="0.0"
        android:startOffset="500"
        android:toAlpha="1.0" />
</set>
res/anim/exit.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <alpha
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="1000"
        android:fillAfter="true"
        android:fromAlpha="1.0"
        android:toAlpha="0" />

</set>

Second step: These animations are item in PopupWindowAnimation style.

res/values/styles.xml
<resources>

    <style name="AppBaseTheme" parent="android:Theme.Light"></style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme"></style>

    <style name="PopupWindowAnimation" parent="android:Animation">
        <item name="android:windowEnterAnimation">@anim/enter</item>
        <item name="android:windowExitAnimation">@anim/exit</item>
    </style>

</resources>

you create the layout with button which show the popup.

res/layout/activity_the_developer_world_is_yours.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <Button
        android:id="@+id/open"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show popup" />

</LinearLayout>

Now you create the layout of popup.

res/layout/popup_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/popupLinearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPopUp"
    android:gravity="center"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPopUpMarcoWindow"
        android:gravity="center"
        android:orientation="vertical" >

        <Button
            android:id="@+id/close"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_marginRight="5dp"
            android:background="@color/colorPopUpMarcoWindow"
            android:text="@string/closebutton" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:background="@color/colorPopUpWindow"
            android:gravity="center"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Popup"
                android:textColor="@color/colorPopUpMarcoWindow" />

            <ImageButton
                android:id="@+id/imageButton1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/octopus_cat" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text="This is a simple popup"
                android:textColor="@color/colorPopUpMarcoWindow" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>
res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">PopUpAndroid</string>
    <string name="title_activity_the_developer_world_is_yours">TheDeveloperWorldIsYours</string>
    <string name="action_settings">Settings</string>
    <string name="closebutton">Close [x]</string>

    <color name="colorPopUp">#BB000000</color>
    <color name="colorPopUpWindow">#000000</color>
    <color name="colorPopUpMarcoWindow">#FFFFFF</color>

</resources>

In conclusion, you create the main class. In this class you create a inflater for show popup.

src/TheDeveloperWorldIsYoursActivity.java
package com.thedeveloperworldisyours.popup;

import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

public class TheDeveloperWorldIsYours extends Activity {
	private Point p;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_the_developer_world_is_yours);
        Button popUpButton = (Button) findViewById(R.id.open);
        popUpButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (p !=null)
				showPopup(TheDeveloperWorldIsYours.this, p);
			}
		});

    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
            int[] location = new int[2];
            Button button = (Button) findViewById(R.id.open);

            button.getLocationOnScreen(location);
            // Initialize the Point with x, and y positions
            p = new Point();
            p.x = location[0];
            p.y = location[1];

    }
 // The method that displays the popup.

    private void showPopup(final Activity context, Point p) {

            Rect rectgle= new Rect();
            Window window= getWindow();
            window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
            int StatusBarHeight= rectgle.top;
            int contentViewTop=
                window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
            int TitleBarHeight= contentViewTop - StatusBarHeight;
            Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
            int popupWidth = display.getWidth();
            int popupHeight = (display.getHeight()-StatusBarHeight);

            // Inflate the popup_layout.xml
            LinearLayout viewGroup = (LinearLayout) context
                            .findViewById(R.id.popupLinearLayout);
            LayoutInflater layoutInflater = (LayoutInflater) context
                            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View layout = layoutInflater.inflate(R.layout.activity_popup, viewGroup);

            // Creating the PopupWindow
            final PopupWindow popup = new PopupWindow(context);
            popup.setContentView(layout);
            popup.setWidth(popupWidth);
            popup.setHeight(popupHeight);
            popup.setFocusable(true);
            popup.setAnimationStyle(R.style.PopupWindowAnimation);

            // Some offset to align the popup a bit to the right, and a bit down,
            // relative to button's position.

            int OFFSET_X = 0;
            int OFFSET_Y = 0;
            // Clear the default translucent background
            popup.setBackgroundDrawable(new BitmapDrawable());
            // Displaying the popup at the specified location, + offsets.
            popup.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y
                            + OFFSET_Y);

            // Getting a reference to Close button, and close the popup when
            // clicked.
            Button close = (Button) layout.findViewById(R.id.close);
            close.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                            popup.dismiss();
                    }
            });

    }

}

You can download this code: Download code

Android App Without Layout

It’s very easy. The most important line of code is:

setContentView(myLInearLayout);

You can download this code: Download code

First step, remove layout.xml. Then in your main class you can programmatically add a LinearLayout, RelativeLayout… a example:

package com.thedeveloperworldisyours.withoutlayout;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class TheDeveloperWorldIsYours extends Activity {

	private TextView valueTV;
	private Button valueB;
	private TextView valueRelativeLayoutTV;
	private Button valueRelativeLayoutB;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//create LInearLayout
		LinearLayout myLInearLayout = new LinearLayout(getApplicationContext());

		//add LayoutParams
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		myLInearLayout.setOrientation(LinearLayout.VERTICAL);

		//set Content View
		setContentView(myLInearLayout);

		//add textView
		valueTV = new TextView(this);
		valueTV.setText("LinearLayout");
		valueTV.setId(5);
		valueTV.setLayoutParams(params);

		// add Button
		valueB = new Button(this);
		valueB.setText("RelativeLayout");
		valueB.setId(5);

		//add the textView and the Button to LinearLayout
		myLInearLayout.addView(valueTV);
		myLInearLayout.addView(valueB);

		valueB.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				// add Button
        		valueRelativeLayoutB = new Button(getApplicationContext());
        		valueRelativeLayoutB.setText("RelativeLayout");
        		valueRelativeLayoutB.setId(5);

        		//add RelativeLayout
				RelativeLayout mainLayout = new RelativeLayout(getApplicationContext());
                RelativeLayout.LayoutParams lyp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
                mainLayout.setLayoutParams(lyp);

                //android:layout_below
        		lyp.addRule(RelativeLayout.BELOW, valueRelativeLayoutB.getId());
        		v.setLayoutParams(lyp);

        		//The most important line
        		setContentView(mainLayout);

              //add textView
                valueRelativeLayoutTV = new TextView(getApplicationContext());
        		valueRelativeLayoutTV.setText("RelativeLayout");
        		valueRelativeLayoutTV.setId(5);
        		valueRelativeLayoutTV.setLayoutParams(lyp);

        		mainLayout.addView(valueRelativeLayoutTV);
        		mainLayout.addView(valueRelativeLayoutB);

        		valueRelativeLayoutB.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						//Exit app
						System.exit(0);
					}
				});

			}
		});

	}

}

You can download this code: Download code

Supporting Different Languages

Android will run on many devices in many regions and therefore, the phone will be in different languages. To reach the most users, your application should handle text and graphics in ways appropriate to the locales where your application will be used.

To add support for more languages, create additional values directories inside res/ that include a hyphen and the ISO country code at the end of the directory name. For example, values-es/ is the directory containing simple resourcess for the Locales with the language code “es”. Android loads the appropriate resources according to the locale settings of the device at run time.

Once you’ve decided on the languages you will support, create the resource subdirectories and string resource files. For example:

MyProject/
    res/
       values/
           strings.xml
       values-es/
           strings.xml

Add the string values for each locale into the appropriate file.

At runtime, the Android system uses the appropriate set of string resources based on the locale currently set for the user’s device.

For example, the following are some different string resource files for different languages.

English (default locale), /values/strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="title">My Application</string>
<string name="hello_world">Hello World!</string>
</resources>

Spanish, /values-es/strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="title">Mi Aplicación</string>
<string name="hello_world">¡Hola Mundo!</string>
</resources>

The same with images

MyProject/
    res/
       drawable/
           background.png
       drawable-es/
           background.xml

You can download this code: Download code

How to transfer data between two activities in android

The following post demonstrates how to use explicit Intents and how to transfer data between two activities.

The first activity will call the second one via an explicit intent. Once the user select the “Back” button on his phone the first activity will receive some hard-coded data from the sub-activity.

You can download this code: example

Create a new Android application.
Create two layouts. The first activity_one.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:tools="http://schemas.android.com/tools"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@drawable/background"
                    android:gravity="center_horizontal"
                    android:orientation="vertical" >

 <TextView android:id="@+id/TextView01"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:minHeight="60dip"
          android:text="@string/text_tv_activity_one"
          android:textSize="20sp" />

 <Button android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:onClick="onClick"
        android:text="@string/title_button_activity_one" />

</LinearLayout>

Create the second layout, your name activity_two.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="wrap_content"
              android:layout_height="match_parent"
              android:background="@drawable/background"
              android:gravity="center_horizontal"
              android:orientation="vertical" >

<LinearLayout android:layout_width="wrap_content"
              android:layout_height="wrap_content" >

<TextView android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/input_one"
          android:textSize="32dip" />

<EditText android:id="@+id/input1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/defaultt" />

</LinearLayout>

<LinearLayout android:layout_width="wrap_content"
              android:layout_height="wrap_content" >

<TextView android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/input_two"
          android:textSize="32dip" />

<EditText android:id="@+id/input2"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/defaultt" />

</LinearLayout>

<Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="@string/finish"
        android:width="80dp" />

</LinearLayout>

Create the following coding for your two activities.


package com.thedeveloperworldisyours.datatransfer;

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

public class ActivityOne extends Activity {

	private static final int REQUEST_CODE = 10;

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

    public void onClick(View view) {
        Intent i = new Intent(this, ActivityTwo.class);
        i.putExtra("Value1", "This value one for ActivityTwo ");
        i.putExtra("Value2", "This value two ActivityTwo");
        // Set the request code to any code you like, you can identify the
        // callback via this code
        startActivityForResult(i, REQUEST_CODE);
      }

      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
          if (data.hasExtra("returnKey1")) {
            Toast.makeText(this, data.getExtras().getString("returnKey1"),
                Toast.LENGTH_SHORT).show();
          }
        }
      }

}

and the second activity.


package com.thedeveloperworldisyours.datatransfer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class ActivityTwo extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_two);
		Bundle extras = getIntent().getExtras();
		if (extras == null) {
			return;
		}
		String value1 = extras.getString("Value1");
		String value2 = extras.getString("Value2");
		if (value1 != null && value2 != null) {
			EditText text1 = (EditText) findViewById(R.id.input1);
			EditText text2 = (EditText) findViewById(R.id.input2);
			text1.setText(value1);
			text2.setText(value2);
		}
	}

	public void onClick(View view) {
		finish();
	}

	@Override
	public void finish() {
		Intent data = new Intent();
		// Return some hard-coded values
		data.putExtra("returnKey1", "Swinging on a star. ");
		data.putExtra("returnKey2", "You could be better then you are. ");
		setResult(RESULT_OK, data);
		super.finish();
	}
}

You can download this code: example