How to change the default transition between activities?

In android the default transition between activities is to slide from left to right.
But with custom animations we can change that.

First create a folder inside the res/drawable folder called “anim”.
Then create a file named “fade.xml” and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromAlpha="0.0" android:toAlpha="1.0"
       android:duration="@android:integer/config_longAnimTime" />

create another file named “hold.xml” in the same place
hold.xml.

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromXDelta="0" android:toXDelta="0"
       android:duration="@android:integer/config_longAnimTime" />

activity_animation.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:text="Sample Animation"/>

    <Button android:id="@+id/fade_animation"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="fade In">
        <requestFocus />
    </Button>
</LinearLayout>

Now the main java file.

package pack.coderzheaven;

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;

public class ActivityAnimation extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_animation);

        Button button = (Button)findViewById(R.id.fade_animation);
        button.setOnClickListener(mFadeListener);
    }

    private OnClickListener mFadeListener = new OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(ActivityAnimation.this, SecondClass.class));
            overridePendingTransition(R.anim.fade, R.anim.hold);
        }
    };
}

package pack.coderzheaven;

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

public class SecondClass extends Activity {
@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"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Second Class"
    />
</LinearLayout>

How to take screenshot of application and store it in SDCARD?

The first part is explained in this Tutorial, that is taking the screenshot of the application (View).

The second part is storing it in the SDCARD. This is possible by compressing the image bitmap to bytes and then store.

 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
         bm.compress(Bitmap.CompressFormat.JPEG, 40, bytes);


         File f = new File(Environment.getExternalStorageDirectory()
                                 + File.separator + "test.jpg");
         try {
			f.createNewFile();
			 FileOutputStream fo = new FileOutputStream(f);
	         fo.write(bytes.toByteArray());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

Finally dont forgot to put the following permission in the manifest file.


 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

How to use shapes in android? A simple example.

In android with shapes we can create beautiful layouts.
Lets look at an example.

Create an xml named “gradient.xml” in your drawable folder and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:angle="0"
        android:startColor="#000000"
        android:endColor="#000000"
        android:centerColor="#97CF4D" />
</shape>

Now the main layout file main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">

    <TextView
        android:text="Sample Text"
        android:id="@+id/text01"
        android:textSize="25sp"
        android:layout_margin="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>
    <View
        android:layout_width="wrap_content"
        android:background="@drawable/gradient"
        android:layout_height="1dp"></View>
   <TextView
        android:text="Sample text"
        android:id="@+id/text02"
        android:textSize="25sp"
        android:layout_margin="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>
    <View
        android:layout_width="wrap_content"
        android:background="@drawable/gradient"
        android:layout_height="1dp"></View>

    <EditText
        android:text=" "
        android:id="@+id/text03"
        android:textSize="25sp"
        android:layout_margin="10dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
    </EditText>
    <View
        android:layout_width="wrap_content"
        android:background="@drawable/gradient"
        android:layout_height="1dp"></View>
</LinearLayout>

The main java file.

package pack.coderzheaven;

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

public class DrawableShapesDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Done. You can now run the application.

Using Shapes

Using Shapes

How to get current time in formatted form in android?

Here is a simple code to get the current time in android in your own format.

long tim=System.currentTimeMillis();
 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
 String curTime =df.format(tim);
 System.out.println("Time : " + curTime);

The output will look like this.


Time : 2011-10-17 09:54:24

How to create a custom ListView in android?

Hello all…..

In today’s tutorial I will show you how to create a custom listview in android.
For that we need 3java files.
One holding the ListView itself another a Model object that holds the data for the listview and the third one for the Adapter which extends the ArrayAdapter class for holding the model.

First the Model.java file

package pack.coderzheaven;

public class Model {

	private String name;
	private String place;
	private boolean selected;

	public Model(String name, String place) {
		this.name = name;
		this.place = place;
		selected = false;
	}

	public String getName() {
		return name;
	}

	public String getPlace() {
		return place;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setPlace(String place) {
		this.place = place;
	}

	public boolean isSelected() {
		return selected;
	}

	public void setSelected(boolean selected) {
		this.selected = selected;
	}

}

Now the second file MyCustomArrayAdapter.java that extends the Arrayadapter class.

package pack.coderzheaven;

import java.util.List;

import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

public class MyCustomArrayAdapter extends ArrayAdapter<Model> {

	private final List<Model> list;
	private final Activity context;

	public MyCustomArrayAdapter(Activity context, List<Model> list) {
		super(context, R.layout.list_layout, list);
		this.context = context;
		this.list = list;
	}

	static class ViewHolder {
		protected TextView text, sub;
		protected CheckBox checkbox;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = null;
		if (convertView == null) {
			LayoutInflater inflator = context.getLayoutInflater();
			view = inflator.inflate(R.layout.list_layout, null);
			final ViewHolder viewHolder = new ViewHolder();
			viewHolder.text = (TextView) view.findViewById(R.id.label);
			viewHolder.text.setTextColor(Color.BLACK);
			viewHolder.sub = (TextView) view.findViewById(R.id.sub);
			viewHolder.sub.setTextColor(Color.GRAY);
			viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
			viewHolder.checkbox
					.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							Model element = (Model) viewHolder.checkbox.getTag();
							element.setSelected(buttonView.isChecked());
							System.out.println("Checked : " + element.getName());
						}
					});
			view.setTag(viewHolder);
			viewHolder.checkbox.setTag(list.get(position));
		} else {
			view = convertView;
			((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
		}
		ViewHolder holder = (ViewHolder) view.getTag();
		holder.text.setText(list.get(position).getName());
		holder.sub.setText(list.get(position).getPlace());
		holder.checkbox.setChecked(list.get(position).isSelected());
		return view;
	}
}

Now the main Java file which is named ModelListViewActivity.java

package pack.coderzheaven;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class ModelListViewActivity extends ListActivity {

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);

		ArrayAdapter<Model> adapter = new MyCustomArrayAdapter(this,	getModel());
		setListAdapter(adapter);
	}

	private List<Model> getModel() {
		List<Model> list = new ArrayList<Model>();
		list.add(get("Android","Google"));
		list.add(get("Windows 7","Microsoft"));
		list.add(get("iPhone","Apple"));
		list.add(get("Ubuntu","Linux"));
		list.add(get("Bada","Samsung"));
		list.add(get("Android","Google"));
		list.add(get("Symbian","Nokia"));
		list.add(get("Windows 7","Microsoft"));
		list.get(1).setSelected(true);	// select one item by default
		return list;
	}

	private Model get(String s,String place) {
		return new Model(s,place);
	}
}

Now the layout for each row in the ListView. – list_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent" android:layout_height="wrap_content">
	<TextView android:text="@+id/label" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:id="@+id/label"
		android:layout_marginLeft="15dp"
		android:layout_marginTop="5dp"
		android:textStyle="bold"
		android:textSize="20px"></TextView>
	<TextView android:text="@+id/sub"
		android:layout_below="@+id/label"
			android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:id="@+id/sub"
		android:layout_marginLeft="15dp"
		android:textSize="15px"></TextView>
	<CheckBox android:id="@+id/check" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:layout_marginLeft="4px"
		android:layout_marginRight="10px" android:layout_alignParentRight="true"
		></CheckBox>
</RelativeLayout>

Now the main.xml file that holds the ListView.

<?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"
    >
	 <ListView
			android:id="@id/android:list"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:background="@drawable/customshape"
			android:dividerHeight="1px"
			android:cacheColorHint="#0000"
			android:clipToPadding="true"
			android:layout_margin="5dp"
			android:soundEffectsEnabled="true"
			android:scrollbars="none">
	</ListView>
</LinearLayout>

customshape.xml (in the drawable folder)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
             <gradient
                android:endColor ="#000000"
                android:startColor="#FFFF0000"
                android:angle="270" />
            <stroke
                android:width="0dp"
                android:color="#C2C2C2" />
            <corners
                android:radius="5dp" />
        </shape>
    </item>   
</selector>

Now the AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="6" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ModelListViewActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>
Custom ListView

Custom ListView

How to get the current version of your application programatically in android?

Here is a sample code to get the version of your application in android.
Try changing the version in the AndroidManifest file and check the result in the console.

package pack.coderzheaven;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;

public class GetVersionDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        int version_no = getVersionNumber(GetVersionDemo.this);
        System.out.println("Version Number : " + version_no);
    }

    public int getVersionNumber(Context context) {
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo("pack.coderzheaven", PackageManager.GET_META_DATA);
            return pInfo.versionCode;
        } catch (NameNotFoundException e) {
            return 0;
        }
    }
}

Note : “pack.coderzheaven” should be replaced by your application package name.

How to check whether your service is running in android?

This example will test whether a service is running in android if you know it’s package name.
Run this sample of code to check this.

private boolean checkMyServiceRunningOrNot() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if ("com.example.your_Service".equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

How to disable any input on the screen in android?

This is a simple example showing how will you disable any input on your current application screen in android.
This is done by showing a transparent overlay dialog on the screen.
This is how it is done.

package pack.coderzheaven;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class DisableInputDemo extends Activity {

	Dialog overlayDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b = (Button)findViewById(R.id.Button01);
        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				disableAnyInput();
			}
		});
    }

    public void disableAnyInput(){
    	Toast.makeText(getApplicationContext(), "This will disable any input. Click the backbutton " +
    					"to enable any input.", Toast.LENGTH_LONG).show();
    	 overlayDialog = new Dialog(DisableInputDemo.this, android.R.style.Theme_Panel);
    	 overlayDialog.setCancelable(true);
         overlayDialog.show();
    }
}

The layout for the above java file- main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="How to disable any input on the screen? Coderzheaven Demo"
    />
<EditText
	android:text=""
	android:hint="Type anything"
	android:id="@+id/EditText01"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content">
</EditText>
<Button
	android:text="Click me to disable any input"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
</LinearLayout>
Disable any input in android

Disable any input in android