Monday, December 31, 2012

Create Dialog with options, using AlertDialog.Builder

Hi Guys!

In this tutorial I am sharing the code about the Alert Dialog with select option in android.
More details about the Alert Dialog visit the android developer site Alert Dialog

Lets start the coding part.

activty_main.xml






MainActivity.java

package com.sunil.alertdialogwithoption;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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

Button buttonStartDialog = (Button)findViewById(R.id.button_alert);
buttonStartDialog.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
StartDialog();
}});
}

private void StartDialog(){
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("My Alert Dialog");
myAlertDialog.setMessage("It provide options for user to select");
myAlertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'Yes' button clicked", Toast.LENGTH_LONG).show();
}
});
myAlertDialog.setNeutralButton("Option 1", new DialogInterface.OnClickListener() {

// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'Option 1' button clicked", Toast.LENGTH_LONG).show();
}
});
myAlertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {

// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'No' button clicked", Toast.LENGTH_LONG).show();
}
});
myAlertDialog.show();
}

}

 You can download the source code Alert Dialog.

Cheers Guys! 

AutoCompleteTextView

Hi Guys!
An AutoComplete TextView is an editable text view that shows completion suggestions automatically while the user is typing. The list of suggestions is displayed in a drop down menu from which the user can choose an item to replace the content of the edit box with.
The drop down can be dismissed at any time by pressing the back key or, if no item is selected in the drop down, by pressing the enter/dpad center key.

FOr detail about the Auto Complete Text View please visit the android developer site AutoCompleteTextView.

Now lets start the coding about the auto text complete view . Here we are getting the item data in array from xml resource.And these array data stored in the adapter.

res/value/myvalues.xml



January
February
March
April
May
June
July
August
September
October
November
December


activity_main.xml









MainActivity.java

package com.sunil.autocompletetext;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class MainActivity extends Activity implements TextWatcher {

AutoCompleteTextView autoCompleteTextView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoCompleteTextView = (AutoCompleteTextView)findViewById(R.id.input);
String[] month = getResources().getStringArray(R.array.month);
autoCompleteTextView.addTextChangedListener(this);
autoCompleteTextView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, month));
}

@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub

}

@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub

}

@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub

}
}

 You can download the source code Auto Complete Text View

Cheers Guys!

Friday, December 28, 2012

Intent of "MediaStore.ACTION_IMAGE_CAPTURE"

Using Intent of "MediaStore.ACTION_IMAGE_CAPTURE", we can request Android build-in Camera App or other Service Provider to take picture.

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="@string/hello"
   />
<Button
   android:id="@+id/captureimage"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Call for ACTION_IMAGE_CAPTURE"
   />
<ImageView
   android:id="@+id/imagecaptured"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   />
</LinearLayout>
 
AndroidImageCapture.java
 
 
 
package com.AndroidImageCapture;
 
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
 
public class AndroidImageCapture extends Activity {
  
 ImageView imageiewImageCaptured;
  
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       Button buttonImageCapture = (Button)findViewById(R.id.captureimage);
       imageiewImageCaptured = (ImageView)findViewById(R.id.imagecaptured);
       
       buttonImageCapture.setOnClickListener(buttonImageCaptureOnClickListener);
   }
   
   Button.OnClickListener buttonImageCaptureOnClickListener
   = new Button.OnClickListener(){
 
  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
   startActivityForResult(intent, 0);
    
  }};
 
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  super.onActivityResult(requestCode, resultCode, data);
   
  if (resultCode == RESULT_OK)
  {
   Bundle extras = data.getExtras();
   Bitmap bmp = (Bitmap) extras.get("data");
   imageiewImageCaptured.setImageBitmap(bmp);
  }
   
 }
}
 

MediaStore.ACTION_IMAGE_CAPTURE
 Cheers Guys!!!!!!!!!!!

I love your comment here...
 

ProgressDialog

Hi Guys!

Today I am going to share the code about the ProgressDialog in android.
A dialog showing a progress indicator and an optional text message or view. Only a text message or a view can be used at the same time.
More About the progress dialog and progress bar then visit the android developer site Progress Dialog.

Now lets start the coding about the progress dialog in android that will execute inside the doInBackground() of Asynctask till.

activity_main.xml








MainActivity.java

package com.sunil.progressdialog;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends Activity {

Button buttonStart;
ProgressBar progressBar;
ProgressDialog progressDialog;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStart = (Button)findViewById(R.id.start);
progressBar = (ProgressBar)findViewById(R.id.progressbar);

buttonStart.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
buttonStart.setClickable(false);
new asyncTaskUpdateProgress().execute();
}

});

}
public class asyncTaskUpdateProgress extends AsyncTask {
int progress1;

@Override
protected void onPostExecute(Void result) {
buttonStart.setClickable(true);
progressDialog.dismiss();
}
@Override
protected void onPreExecute() {
progress = 0;
progressDialog = ProgressDialog.show(MainActivity.this, "ProgressDialog", "Running");
}
@Override
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
}
@Override
protected Void doInBackground(Void... arg0) {
while(progress1<100 data-blogger-escaped-null="" data-blogger-escaped-pre="" data-blogger-escaped-progress1="" data-blogger-escaped-publishprogress="" data-blogger-escaped-return="" data-blogger-escaped-systemclock.sleep=""> 
 You can download the source code Progress Dialog
 
Cheers Guys! 

Spinner

Hi Guys!!

Today I am sharing the code about the Spinner in android.
Spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one.
For detail please visit android developer site Spinner.

So lets start the coding about the spinner in android.

activity_main.xml









MainActivity.java

package com.sunil.spinner;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivity extends Activity {

private static final String[] dayOfWeek =
{"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
private ArrayAdapter adapter;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner)findViewById(R.id.spinner);

adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, dayOfWeek);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
}

 You can download the source code Spinner. 

Cheers Guys!!

TimePickerDialog

Hi Guys!

A view for selecting the time of day, in either 24 hour or AM/PM mode. The hour, each minute digit, and AM/PM (if applicable) can be conrolled by vertical spinners. The hour can be entered by keyboard input. Entering in two digit hours can be accomplished by hitting two digits within a timeout of about a second . The minutes can be entered by entering single digits.

For more details you can visit the android developer site Timer Picker
Now lets start the coding about the Time Picker android.

acivity_main.xml







MainActivity.java

package com.sunil.timepickerdialog;

import java.util.Calendar;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

private int hour, minute;
static final int ID_TIMEPICKER = 0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button startTimePicker = (Button)findViewById(R.id.starttimepicker);
startTimePicker.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {

final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
showDialog(ID_TIMEPICKER);
}});
}
@Override
protected Dialog onCreateDialog(int id) {

switch(id){
case ID_TIMEPICKER:
return new TimePickerDialog(this, timeSetListener, hour, minute, false);
default:
return null;
}
}
private TimePickerDialog.OnTimeSetListener timeSetListener
= new TimePickerDialog.OnTimeSetListener(){
@Override
public void onTimeSet(android.widget.TimePicker arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), String.valueOf(arg1) + ":" + String.valueOf(arg2), Toast.LENGTH_LONG).show();
}};
}


 You can download the source code Time Picker

DatePickerDialog

Hi Guys!
Today I am going to share about the code of Date Picker in Android.
This class is a widget for selecting a date. The date can be selected by a year, month, and day spinners or a CalendarView. The set of spinners and the calendar view are automatically synchronized. The client can customize whether only the spinners, or only the calendar view, or both to be displayed. Also the minimal and maximal date from which dates to be selected can be customized.
For detail about the Date Picker you can visit the android developer site Date Picker.

So lets start the coding about the date picker android.

activity_main.xml







MainAcivity.java

package com.sunil.datepicker;

import java.util.Calendar;

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

public class MainActivity extends Activity {

private int year, month, day;
static final int ID_DATEPICKER = 0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button startDatePicker = (Button)findViewById(R.id.startdatepicker);
startDatePicker.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
showDialog(ID_DATEPICKER);
}});
}

@Override
protected Dialog onCreateDialog(int id) {
switch(id){
case ID_DATEPICKER:
return new DatePickerDialog(this, dateSetListener, year, month, day);
default:
return null;
}
}

private DatePickerDialog.OnDateSetListener dateSetListener
= new DatePickerDialog.OnDateSetListener(){

@Override
public void onDateSet(android.widget.DatePicker arg0, int arg1,int arg2, int arg3) {

Toast.makeText(getBaseContext(), String.valueOf(arg1) + "/" + String.valueOf(arg2+1) + "/" + String.valueOf(arg3),Toast.LENGTH_LONG).show();
}
};
}


You can download the source code Date Picker

Wednesday, December 26, 2012

Custom dialog

Hi Guys!!
Today I am sharing the code about the custom dialog with by using the inflater.
we can make the layout inflate on the view. By help of the Alert Dialog we can create the custom the Alert Dialog .
More about the Alert Dialog you can visit the android developer site Alert Dialog.

So lets start the coding for custom dialog with help of inflater.
 

activity_main.xml








MainActivity.java

package com.sunil.customdialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {

void openCustomDialog(){
AlertDialog.Builder customDialog = new AlertDialog.Builder(MainActivity.this);
customDialog.setTitle("Custom Dialog");
LayoutInflater layoutInflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=layoutInflater.inflate(R.layout.activity_main,null);

Button btn = (Button)view.findViewById(R.id.idButton);
btn.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Button Pressed", Toast.LENGTH_LONG).show();
}});

customDialog.setPositiveButton("OK", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface arg0, int arg1) {

}});

customDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface arg0, int arg1) {

}});
customDialog.setView(view);
customDialog.show();
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openCustomDialog();
}
}

 
 You can download the source code Custom Dialog

ListView with multiple choice

Hi Guys!!
Today i am sharing the code of the multiple choice option select in list view.
ListView is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database query and converts each item result into a view that's placed into the list. 
For more details about the List View visit the Android Developer site List View.

Lets Start the coding now.


activty_main.xml






MainActivity.java

package com.sunil.listview;

import android.app.Activity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

ListView myList;
Button getChoice;

String[] listContent = {

"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"

};

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList = (ListView)findViewById(R.id.list);
getChoice = (Button)findViewById(R.id.getchoice);

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, listContent);
myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

myList.setAdapter(adapter);
getChoice.setOnClickListener(new Button.OnClickListener(){


@Override
public void onClick(View v) {

String selected = "";
int cntChoice = myList.getCount();

SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++){
if(sparseBooleanArray.get(i)) {
selected += myList.getItemAtPosition(i).toString() + "\n";

}

}

Toast.makeText(MainActivity.this, selected, Toast.LENGTH_LONG).show();

}});

}

}

Please download the source code ListView with multiple choice

 Cheers Guys!!

Sunday, December 23, 2012

Start Activity from Broadcast Recevier


Some time we need to start an Activity from Broadcast Receiver..
how can we achieve this i am going to write step by step.

So lets create a small App to do this things 

-------------------------------------------
App Name: BReceiver2Activity
Package Name: com.sunil
Android SDK: Android SDK 2.2 / API 8
-------------------------------------------

MyReceiver.java
  1. package com.sunil;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.util.Log;  
  7. import android.widget.Toast;  
  8.   
  9. public class MyReceiver extends BroadcastReceiver {  
  10.   
  11.  @Override  
  12.  public void onReceive(Context context, Intent intent) {  
  13.     
  14.   Toast.makeText(context, "MyReceiver Started",   
  15.     Toast.LENGTH_SHORT).show();  
  16.   Log.v("Info Message""in Broadcast receiver");  
  17.   Intent myIntent=new Intent(context,MyActivity.class);   
  18.   myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  19.   context.startActivity(myIntent);  
  20.  }  
  21.   
  22. }  

MyActivity.java
  1. package com.sunil;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5.   
  6. public class MyActivity extends Activity {  
  7.   
  8.  @Override  
  9.  public void onCreate(Bundle savedInstanceState) {  
  10.   super.onCreate(savedInstanceState);  
  11.   setContentView(R.layout.main);  
  12.   
  13.  }  
  14. }  

main.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.  xmlns:android="http://schemas.android.com/apk/res/android"  
  4.  android:orientation="vertical"  
  5.  android:layout_width="fill_parent"  
  6.  android:layout_height="fill_parent"  
  7.  android:weightSum="1">  
  8.  <TextView  
  9.   android:layout_width="fill_parent"  
  10.   android:layout_height="wrap_content"  
  11.   android:text="@string/hello"  
  12.   android:layout_weight="0.14" />  
  13. </LinearLayout>  

AndroidManifest.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest  
  3.  xmlns:android="http://schemas.android.com/apk/res/android"  
  4.  package="com.sunil"  
  5.  android:versionCode="1"  
  6.  android:versionName="1.0">  
  7.  <uses-sdk android:minSdkVersion="8" />  
  8.   
  9.  <application  
  10.   android:icon="@drawable/icon"  
  11.   android:label="@string/app_name">  
  12.   
  13.   <activity  
  14.    android:enabled="true"  
  15.    android:name=".MyActivity">  
  16.    <intent-filter>  
  17.     <action android:name="com.sunil.MyActivity">  
  18.     </action>  
  19.    </intent-filter>  
  20.   </activity>  
  21.   
  22.   <receiver  
  23.     android:enabled="true"  
  24.     android:name=".MyReceiver">  
  25.     <intent-filter>  
  26.     <action android:name="android.intent.action.BOOT_COMPLETED" />  
  27.     </intent-filter>  
  28.   </receiver>  
  29.   
  30.  </application>  
  31. </manifest>  

Now Reboot Emulator, Activity will appear on start-up.

You can download source code here: BReceiver2Activity

cheers!!

I'd love to hear your thoughts!!

Grid View Demo With Images

GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.

We are going to create a Grid View to show Images, where we can select each item via click.

so lets create simple app with default activity "GridViewActivity" and put this code inside it.   
  1. package com.sunil;
  2. import android.app.Activity;  
  3. import android.os.Bundle;  
  4. import android.view.View;  
  5. import android.widget.AdapterView;  
  6. import android.widget.GridView;  
  7. import android.widget.TextView;  
  8. import android.widget.Toast;  
  9. import android.widget.AdapterView.OnItemClickListener;  
  10.   
  11. public class GridViewActivity extends Activity {  
  12.       
  13.  GridView gridView;  
  14.    
  15.  static final String[] MOBILE_OS = new String[]{  
  16.   "Android""iOS""Windows""Balckberry",  
  17.  };  
  18.    
  19.     @Override  
  20.     public void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.main);  
  23.           
  24.         gridView = (GridView) findViewById(R.id.gridView1);  
  25.           
  26.         gridView.setAdapter(new ImageAdapter(this, MOBILE_OS));  
  27.           
  28.         gridView.setOnItemClickListener(new OnItemClickListener(){  
  29.          public void onItemClick(AdapterView parent, View v,   
  30.            int position, long id){  
  31.           Toast.makeText(getApplicationContext(),  
  32.           ((TextView) v.findViewById(R.id.grid_item_label))  
  33.           .getText(), Toast.LENGTH_SHORT).show();  
  34.          }  
  35.         });  
  36.     }  
  37. }  

ImageAdapter.java
   
  1. package com.sunil;  
  2. import android.content.Context;  
  3. import android.view.LayoutInflater;  
  4. import android.view.View;  
  5. import android.view.ViewGroup;  
  6. import android.widget.BaseAdapter;  
  7. import android.widget.ImageView;  
  8. import android.widget.TextView;  
  9.   
  10. public class ImageAdapter extends BaseAdapter{  
  11.    
  12.    
  13.  private Context context;  
  14.  private final String[] mobileValues;  
  15.    
  16.  public ImageAdapter(Context context, String[]   
  17.    mobileValues){  
  18.   this.context=context;  
  19.   this.mobileValues=mobileValues;  
  20.  }  
  21.    
  22.  public View getView(int position, View convertView,   
  23.    ViewGroup parent){  
  24.   LayoutInflater inflater = (LayoutInflater) context  
  25.     .getSystemService(Context.  
  26.       LAYOUT_INFLATER_SERVICE);  
  27.     
  28.   View gridView;  
  29.   if(convertView == null){  
  30.    gridView = new View(context);  
  31.    gridView = inflater.inflate(  
  32.      R.layout.mobile, null);  
  33.      
  34.    TextView textView = (TextView) gridView.  
  35.      findViewById(R.id.grid_item_label);  
  36.    textView.setText(mobileValues[position]);  
  37.      
  38.    ImageView imageView = (ImageView) gridView.  
  39.      findViewById(  
  40.        R.id.grid_item_image);  
  41.    String mobile = mobileValues[position];  
  42.     
  43.    if(mobile.equals("Android")){  
  44.     imageView.setImageResource(  
  45.       R.drawable.android_logo);  
  46.    }  
  47.    else if(mobile.equals("iOS")){  
  48.     imageView.setImageResource(  
  49.       R.drawable.ios_logo);  
  50.    }  
  51.    else if(mobile.equals("Windows")){  
  52.     imageView.setImageResource(  
  53.       R.drawable.windows_logo);      
  54.    }     
  55.    else if(mobile.equals("BlackBerry")){  
  56.     imageView.setImageResource(  
  57.       R.drawable.ios_logo);  
  58.    }     
  59.   }  
  60.   else{  
  61.    gridView = (View) convertView;  
  62.   }  
  63.   return gridView;  
  64.  }  
  65.   
  66.  @Override  
  67.  public int getCount() {  
  68.   // TODO Auto-generated method stub  
  69.   return mobileValues.length;  
  70.  }  
  71.   
  72.  @Override  
  73.  public Object getItem(int position) {  
  74.   // TODO Auto-generated method stub  
  75.   return null;  
  76.  }  
  77.   
  78.  @Override  
  79.  public long getItemId(int position) {  
  80.   // TODO Auto-generated method stub  
  81.   return 0;  
  82.  }  
  83. }  

main.xml
 
  1. <gridview android:columnwidth="100dp" android:gravity="center" android:id="@+id/gridView1" android:layout_height="fill_parent" android:layout_width="fill_parent" android:numcolumns="1" android:stretchmode="columnWidth" xmlns:android="http://schemas.android.com/apk/res/android">  
  2.  </gridview>  

mobile.xml
  1.   
  2. <linearlayout android:layout_height="wrap_content" android:layout_width="wrap_content" android:orientation="horizontal" android:padding="5dp" xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     
  4.   <imageview android:id="@+id/grid_item_image" android:layout_height="50px" android:layout_marginright="10px" android:layout_width="50px" android:src="@drawable/blackberry_logo">  
  5.   </imageview>  
  6.     
  7.   <textview android:id="@+id/grid_item_label" android:layout_height="wrap_content" android:layout_margintop="5px" android:layout_width="wrap_content" android:text="@+id/label" android:textsize="15px">  
  8.   </textview>     
  9.       
  10. </linearlayout>  

you need to put these icons in res/drawable-mdpi folder or any:

Then our output is:

Android Animation App - Bouncing Ball

So looking for play with animation stuff.. good!! you are on right place  :)
today we are going to learn how to create simple android animation app.
so in this application we will create Background View and Ball programatically which will jump.

let's began the code, first of all we need to create simple android app having single Activity
name is :
BouncingBallActivity.java


  1. package com.mytest;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6.   
  7. public class BouncingBallActivity extends Activity {  
  8.     /** Called when the activity is first created. */  
  9.     @Override  
  10.     public void onCreate(Bundle savedInstanceState) {  
  11.         super.onCreate(savedInstanceState);  
  12.         //setContentView(R.layout.main);  
  13.           
  14.         View bouncingBallView = new BouncingBallView(this);  
  15.         setContentView(bouncingBallView);  
  16.     }  
  17. }  

Now we need to create a View programatically [we will not using any xml file]
here we go..
BouncingBallView.java
  1.     
  2. package com.mytest;  
  3.     
  4. import android.content.Context;  
  5. import android.graphics.Canvas;  
  6. import android.graphics.Color;  
  7. import android.graphics.Paint;  
  8. import android.graphics.RectF;  
  9. import android.view.KeyEvent;  
  10. import android.view.View;  
  11.      
  12. public class BouncingBallView extends View {  
  13.    private int xMin = 0;          // This view's bounds  
  14.    private int xMax;  
  15.    private int yMin = 0;  
  16.    private int yMax;  
  17.    private float ballRadius = 40// Ball's radius  
  18.    private float ballX = ballRadius + 20;  // Ball's center (x,y)  
  19.    private float ballY = ballRadius + 40;  
  20.    private float ballSpeedX = 5;  // Ball's speed (x,y)  
  21.    private float ballSpeedY = 3;  
  22.    private RectF ballBounds;      // Needed for Canvas.drawOval  
  23.    private Paint paint;           // The paint (e.g. style, color) used for drawing  
  24.      
  25.    // Constructor  
  26.    public BouncingBallView(Context context) {  
  27.       super(context);  
  28.       ballBounds = new RectF();  
  29.       paint = new Paint();  
  30.         
  31.       //to enable keypad  
  32.       this.setFocusable(true);  
  33.       this.requestFocus();  
  34.    }  
  35.     
  36.    // Called back to draw the view. Also called by invalidate().  
  37.    @Override  
  38.    protected void onDraw(Canvas canvas) {  
  39.       // Draw the ball  
  40.       ballBounds.set(ballX-ballRadius, ballY-ballRadius, ballX+ballRadius, ballY+ballRadius);  
  41.       paint.setColor(Color.GREEN);  
  42.       canvas.drawOval(ballBounds, paint);  
  43.           
  44.       // Update the position of the ball, including collision detection and reaction.  
  45.       update();  
  46.     
  47.       // Delay  
  48.       try {    
  49.          Thread.sleep(60);    
  50.       } catch (InterruptedException e) { }  
  51.         
  52.       invalidate();  // Force a re-draw  
  53.    }  
  54.      
  55.    // Detect collision and update the position of the ball.  
  56.    private void update() {  
  57.       // Get new (x,y) position  
  58.      // ballX += ballSpeedX;  
  59.       ballY += ballSpeedY;  
  60.       // Detect collision and react  
  61.       if (ballX + ballRadius > xMax) {  
  62.          ballSpeedX = -ballSpeedX;  
  63.          ballX = xMax-ballRadius;  
  64.       } else if (ballX - ballRadius < xMin) {  
  65.          ballSpeedX = -ballSpeedX;  
  66.          ballX = xMin+ballRadius;  
  67.       }  
  68.       if (ballY + ballRadius > yMax) {  
  69.          ballSpeedY = -ballSpeedY;  
  70.          ballY = yMax - ballRadius;  
  71.       } else if (ballY - ballRadius < yMin) {  
  72.          ballSpeedY = -ballSpeedY;  
  73.          ballY = yMin + ballRadius;  
  74.       }  
  75.    }  
  76.      
  77.    // Called back when the view is first created or its size changes.  
  78.    @Override  
  79.    public void onSizeChanged(int w, int h, int oldW, int oldH) {  
  80.       // Set the movement bounds for the ball  
  81.       xMax = w-1;  
  82.       yMax = h-1;  
  83.    }  
  84.      
  85.    // key-up event handler  
  86.    @Override  
  87.    public boolean onKeyUp(int keyCode, KeyEvent event) {  
  88.       switch (keyCode) {  
  89.          case KeyEvent.KEYCODE_DPAD_RIGHT: // Increase rightward speed  
  90.             ballSpeedX++;  
  91.             break;  
  92.          case KeyEvent.KEYCODE_DPAD_LEFT:  // Increase leftward speed  
  93.             ballSpeedX--;  
  94.             break;  
  95.          case KeyEvent.KEYCODE_DPAD_UP:    // Increase upward speed  
  96.             ballSpeedY--;  
  97.             break;  
  98.          case KeyEvent.KEYCODE_DPAD_DOWN:  // Increase downward speed  
  99.             ballSpeedY++;  
  100.             break;  
  101.          case KeyEvent.KEYCODE_DPAD_CENTER: // Stop  
  102.             ballSpeedX = 0;  
  103.             ballSpeedY = 0;  
  104.             break;  
  105.          case KeyEvent.KEYCODE_A:    // Zoom in  
  106.             // Max radius is about 90% of half of the smaller dimension  
  107.             float maxRadius = (xMax > yMax) ? yMax / 2 * 0.9f  : xMax / 2 * 0.9f;  
  108.             if (ballRadius < maxRadius) {  
  109.                ballRadius *= 1.05;   // Increase radius by 5%  
  110.             }  
  111.             break;  
  112.          case KeyEvent.KEYCODE_Z:    // Zoom out  
  113.             if (ballRadius > 20) {   // Minimum radius  
  114.                ballRadius *= 0.95;   // Decrease radius by 5%  
  115.             }  
  116.             break;  
  117.       }  
  118.       return true;  // Event handled  
  119.    }  
  120.      
  121.      
  122. }  
at last our manifest file should look like this..
AndroidManifest.xml

  1.     
  2.   
  3. <manifest android:versioncode="1" android:versionname="1.0" package="com.mytest" xmlns:android="http://schemas.android.com/apk/res/android">  
  4.     <uses-sdk android:minsdkversion="8">  
  5.   
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7.         <activity android:label="@string/app_name" android:name=".BouncingBallActivity">  
  8.             <intent-filter>  
  9.                 <action android:name="android.intent.action.MAIN">  
  10.                 <category android:name="android.intent.category.LAUNCHER">  
  11.             </category></action></intent-filter>  
  12.         </activity>  
  13.   
  14.     </application>  
  15. </uses-sdk></manifest>  

output is like this

we have done great job on ma B'day!!   :D

cheers!!

I'd love to here your thoughts!

 

Copyright @ 2013 Android Developers Tipss.