Monday, June 25, 2012

Android SpannableStringBuilder Example



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

<EditText 
        android:id="@+id/editText1"
        android:layout_marginTop="10dp"
        android:layout_width="fill_parent"
        android:textSize="50.0dp"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
<TextView 
        android:id="@+id/txtview"
        android:layout_width="fill_parent"
        android:textSize="25.0dp"
        android:gravity="center"
        android:layout_height="wrap_content"
        android:text="SpannableStringBuilder" />
</LinearLayout>




SpannableStringBuilderActivity.java:
public class SpannableStringBuilderActivity extends Activity {
 private EditText et;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  et = (EditText) this.findViewById(R.id.editText1);
  et.setText("HelloWorld");
  this.setstyle(3, 7);
    }
 public void setstyle(int start, int end) {
  SpannableStringBuilder spannable = new SpannableStringBuilder(getText()
    .toString());
  CharacterStyle span1 = new UnderlineSpan();
  spannable.setSpan(span1, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  ForegroundColorSpan span2 = new ForegroundColorSpan(Color.RED);
  spannable.setSpan(span2, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
   CharacterStyle span3=new StyleSpan(android.graphics.Typeface.ITALIC); 
   spannable.setSpan(span3, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  setText(spannable);
 }
 private Editable getText() {
  return et.getText();
 }

 private void setText(SpannableStringBuilder spannalbe) {
  et.setText(spannalbe);

 }
}


Download Source Code: SpannableStringBuilder









Android TextWatcher Example



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

    <EditText 
        android:id="@+id/entry"
        android:layout_marginTop="10dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
<TextView 
        android:id="@+id/txtview1"
        android:layout_width="fill_parent"
        android:textSize="25.0dp"
        android:gravity="center"
        android:layout_height="wrap_content"
        android:text="TextWatcher" />
</LinearLayout>


MaxLengthWatcher.java:
public class MaxLengthWatcher implements TextWatcher {  
  
    private int maxLen = 0;  
    private EditText editText = null;  
      
      
    public MaxLengthWatcher(int maxLen, EditText editText) {  
        this.maxLen = maxLen;  
        this.editText = editText;  
    }  
  
    public void afterTextChanged(Editable arg0) {  
        // TODO Auto-generated method stub  
          
    }  
  
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,  
            int arg3) {  
        // TODO Auto-generated method stub  
          
    }  
  
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {  
        // TODO Auto-generated method stub  
        Editable editable = editText.getText();  
        int len = editable.length();  
          
        if(len > maxLen)  
        {  
            int selEndIndex = Selection.getSelectionEnd(editable);  
            String str = editable.toString();  
            //Interception of a new string 
            String newStr = str.substring(0,maxLen);  
            editText.setText(newStr);  
            editable = editText.getText();           
            int newLen = editable.length();  
            if(selEndIndex > newLen)  
            {  
                selEndIndex = editable.length();  
            }  
            //Set the new cursor position 
            Selection.setSelection(editable, selEndIndex);  
              
        }  
    }  
}


TextWatcherActivity.java :
public class TextWatcherActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        EditText editText = (EditText) findViewById(R.id.entry);  
        editText.addTextChangedListener(new MaxLengthWatcher(10, editText));  
    }
}


Download Source Code: AndroidTextWatcher









Android ImageSpan Example



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

<EditText 
        android:id="@+id/editText1"
        android:layout_marginTop="10dp"
        android:layout_width="fill_parent"
        android:minLines="6"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
<TextView 
        android:id="@+id/txtview"
        android:layout_width="fill_parent"
        android:textSize="25.0dp"
        android:gravity="center"
        android:layout_height="wrap_content"
        android:text="ImageSpan" />
</LinearLayout>


ImageSpanActivity.java:
public class ImageSpanActivity extends Activity {
 private EditText ettxt;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ettxt = (EditText) this.findViewById(R.id.editText1);
        ettxt.setText("HelloWorld");
        
        Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
  drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
    drawable.getIntrinsicHeight());
  SpannableString spannable = new SpannableString(getText()
    .toString() + "[smile]");
  ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
  spannable.setSpan(span, getText().length(),
    getText().length() + "[smile]".length(),
    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
  setText(spannable);
    }
 private Editable getText() {
  return ettxt.getText();
 }

 private void setText(SpannableString spannalbe) {
  ettxt.setText(spannalbe);

 }
}


Download Source Code: AndroidImageSpan









Android InputFilter Example





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

    <EditText    
        android:id="@+id/edit_text"  
        android:layout_marginTop="10dp"    
        android:layout_width="fill_parent"     
        android:layout_height="wrap_content"    
       />  
    <Button
        android:id="@+id/btnId"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Lock/Unlock" />
<TextView 
        android:id="@+id/txtview"
        android:layout_width="fill_parent"
        android:textSize="25.0dp"
        android:gravity="center"
        android:layout_height="wrap_content"
        android:text="InputFilter" />
</LinearLayout>



InputFilterActivity.java:
public class InputFilterActivity extends Activity {

    private EditText editText;    
    private boolean value = false; 
    Button b;
    String str = "Hello,Android!"; 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        editText=(EditText)findViewById(R.id.edit_text);  
        editText.setText("EditText component");  
         b = (Button) findViewById(R.id.btnId);    
        b.setText("Lock");    
        b.setOnClickListener(new View.OnClickListener() {         
            @Override    
            public void onClick(View v) {    
                if (value) {    
                    value = false; 
                    b.setText("Lock");
                } else {    
                    value = true;  
                    b.setText("Unlock");
                }    
                lockUnlock(value);    
            }    
        });  
    }
    private void lockUnlock(boolean value) {    
        if (value) {    
            editText.setFilters(new InputFilter[] { new InputFilter() {    
                @Override    
                public CharSequence filter(CharSequence source, int start,    
                        int end, Spanned dest, int dstart, int dend) {    
                    return source.length() < 1 ? dest.subSequence(dstart, dend)    
                                : "";    
                }    
            } });    
        } else {    
            editText.setFilters(new InputFilter[] { new InputFilter() {    
                @Override    
                public CharSequence filter(CharSequence source, int start,    
                        int end, Spanned dest, int dstart, int dend) {    
                     return null;    
                }    
            } });    
        }    
    }    
}


Download Source Code: AndroidInputFilter









Sunday, June 17, 2012

Android: Toast Example

In Android,Toast is a notification message that usees to displays a message to the user and message will disappear automatically after a certain period of time. Information can be simple text, it can be complex pictures and other content (shows a view) .

Android_Toast_Example Android_Toast_Example


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

<Button android:id="@+id/button1"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Toast View"
/>
<Button android:id="@+id/button2"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text=" Custom Toast View"
/>
</LinearLayout>


Add Layout for Toast my_toast.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/toast_border_one" >
    <ImageView 
        android:src="@drawable/warning"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
<TextView
    android:layout_width="wrap_content" 
    android:id="@+id/TextViewInfo"
    android:layout_height="wrap_content" 
    android:text="Your error message here"
    android:layout_gravity="center_vertical"
     >  
</TextView>
</LinearLayout>


ToastActivity.java:
public class ToastActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
     Button btnone=(Button)findViewById(R.id.button1);
     btnone.setOnClickListener(btnoneListner);
     
     Button btntwo=(Button)findViewById(R.id.button2);
     btntwo.setOnClickListener(btntwoListner);
    }
    OnClickListener btnoneListner=new OnClickListener() {
  
  @Override
  public void onClick(View v) {
   // TODO Auto-generated method stub
   Toast.makeText(ToastActivity.this,"Your Text
           Here",Toast.LENGTH_LONG).show();
  }
 };
    OnClickListener btntwoListner=new OnClickListener() {
  
  @Override
  public void onClick(View v) {
   // TODO Auto-generated method stub
   showToast();
  }
 };
 public void showToast()
 {
       View toastRoot = getLayoutInflater()
                            .inflate(R.layout.my_toast, null);
       Toast toast=new Toast(getApplicationContext());
       toast.setView(toastRoot);
       toast.setGravity(Gravity.CENTER, 0, 40);
       toast.setDuration(Toast.LENGTH_LONG);
       TextView tv=(TextView)toastRoot.findViewById(R.id.TextViewInfo);
       tv.setText("Your error message here");
       toast.show();
 }
}


Download Source Code: CustomToast









Tuesday, June 12, 2012

Android Spinner Example

Spinner is a widget similar to a drop-down list for selecting items.

In this post, you'll create a simple spinner widget that displays a list of countries and implements OnItemSelectedListener When item is selected, a toast message will display the selected item.

STEP 1: Start a new project named AndroidSpinnerExample.

STEP 2: Open the res\layout\main.xml file and insert the following code:
<xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >
 <Spinner 
 android:id="@+id/spinnertest" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content"
 android:entries="@+array/country_labels"
 />
 <Button
 android:id = "@+id/btn_OK"
 android:layout_width = "wrap_content"
 android:layout_height = "wrap_content"
 android:text = " OK "
 />
 <TextView 
    android:id="@+id/txtselecteditem"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Imran khan's Android"
    android:textSize="30dp"
    />
</LinearLayout>


Android_Spinner_Example_Imran_Khan_Android Android_Spinner_Example_Imran_Khan_Android

STEP 3: Add new arrays.xml in res/values/ and put following string array:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="country_labels">
<item>Afghanistan</item>
<item>Bangladesh</item>
<item>Bhutan</item>
<item>Nepal</item>
<item>Hindustan (Bharat)</item>
<item>Iran</item>
</string-array>
</resources>

STEP 4: SpinnerActivity implements OnItemSelectedListener to get selected item from Spinner as:
public class SpinnerActivity extends Activity 
        implements OnItemSelectedListener {
 private Spinner Spinnerexp;
 private Button btn;
 private TextView txtview;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Spinnerexp = (Spinner)findViewById(R.id.spinnertest);
        btn = (Button)findViewById(R.id.btn_OK);
        txtview=(TextView)findViewById(R.id.txtselecteditem);
        btn.setOnClickListener(ocl);
        Spinnerexp.setOnItemSelectedListener(this);
    }
    private Button.OnClickListener ocl = new Button.OnClickListener(){
     public void onClick(View v){
     String choseValue = Spinnerexp.getSelectedItem().toString();
     Toast.makeText(SpinnerActivity.this, choseValue, 
        Toast.LENGTH_SHORT).show();
     }
     };
 @Override
 public void onItemSelected(AdapterView arg0, 
          View arg1, int arg2,long arg3) {
  // Get Selected Text From Spinner
     String choseValue = Spinnerexp.getSelectedItem().toString();
     txtview.setText(choseValue);
 }
 @Override
 public void onNothingSelected(AdapterView arg0) {
  // TODO Auto-generated method stub
  
 }
}



Download Source Code: AndroidSpinnerExample









Thursday, June 7, 2012

Android GridView Example



Android_GridView_Example_Imran_Khan_Android Android_GridView_Example_Imran_Khan_Android

In res/layout/main.xml layout add GridView as :
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"   
    android:id="@+id/grdview"  
    android:paddingTop="20dp"
    android:layout_width="fill_parent"   
    android:layout_height="fill_parent"  
    android:numColumns="auto_fit"  
    android:verticalSpacing="40dp"  
    android:horizontalSpacing="30dp"  
    android:columnWidth="90dp"  
    android:stretchMode="columnWidth"  
    android:gravity="center"  
/> 

In res/layout/ Create an gridviewitem.xml layout for GridView items as :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:paddingBottom="5dip"
    android:layout_height="fill_parent" >
    
         <ImageView   
               android:layout_height="wrap_content"   
               android:id="@+id/grditemimg"   
               android:layout_width="wrap_content"   
               android:layout_centerHorizontal="true">   
         </ImageView>  
         
         <TextView   
               android:layout_width="wrap_content"   
               android:layout_below="@+id/grditemimg"   
               android:layout_height="wrap_content"   
               android:text="TextView01"   
               android:layout_centerHorizontal="true"   
               android:id="@+id/grditemtxt">  
         </TextView>

</RelativeLayout>

In GridViewActivity :
public class GridViewActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Remove title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //Remove notification bar
        this.getWindow().setFlags(WindowManager.LayoutParams.
       FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
        GridView gridview = (GridView) findViewById(R.id.grdview);  
        ArrayList<HashMap<String, Object>> lstImageItem =
             new ArrayList<HashMap<String, Object>>(); 

        HashMap<String,Object> map = new HashMap<String,Object>();
             map.put("itemimg", R.drawable.v01);
             map.put("itemtxt", "Blogger");
             lstImageItem.add(map); 
             map = new HashMap();
             map.put("itemimg", R.drawable.v02);
             map.put("itemtxt", "Facebook");
             lstImageItem.add(map); 
             map = new HashMap();
             map.put("itemimg", R.drawable.v03);
             map.put("itemtxt", "Flickr");
             lstImageItem.add(map); 
             map = new HashMap();
             map.put("itemimg", R.drawable.v04);
             map.put("itemtxt", "Hi5");
             lstImageItem.add(map); 
             map = new HashMap();
             map.put("itemimg", R.drawable.v05);
             map.put("itemtxt", "Linkedin");
             lstImageItem.add(map); 
             map = new HashMap();
             map.put("itemimg", R.drawable.v06);
             map.put("itemtxt", "Netvibes");
             lstImageItem.add(map); 
        SimpleAdapter saImageItems = new SimpleAdapter(this,
                lstImageItem,
                R.layout.gridviewitem,       
                new String[] {"itemimg","itemtxt"},   
                new int[] {R.id.grditemimg,R.id.grditemtxt});  
gridview.setAdapter(saImageItems);  

gridview.setOnItemClickListener(new ItemClickListener());
        
    }
    class  ItemClickListener implements OnItemClickListener  
    {  

 @SuppressWarnings("unchecked")
 @Override
 public void onItemClick(AdapterView arg0, 
           View arg1, int arg2, long arg3) {
 // TODO Auto-generated method stub
 HashMap<String, Object> item=
         (HashMap<String, Object>) arg0.getItemAtPosition(arg2);  
      
 Toast.makeText(GridViewActivity.this, 
        (String)item.get("itemtxt"), Toast.LENGTH_SHORT).show();
 setTitle((String)item.get("itemtxt"));  
        } 
   }
}


Download Source Code: GridViewExample









Monday, June 4, 2012

Android SlidingDrawer Example




SlidingDrawer hides content out of the screen and allows the user to drag a handle to bring the content on screen. SlidingDrawer can be used vertically or horizontally. A special widget composed of two children views: the handle, that the users drags, and the content, attached to the handle and dragged with it. SlidingDrawer should be used as an overlay inside layouts. This means SlidingDrawer should only be used inside of a FrameLayout or a RelativeLayout for instance. The size of the SlidingDrawer defines how much space the content will occupy once slid out so SlidingDrawer should usually use match_parent for both its dimensions. Inside an XML layout, SlidingDrawer must define the id of the handle and of the content.
Two important methods of SlidingDrawer :

In res/layout/main.xm layout add SlidingDrawer View as :
<?xml version="1.0" encoding="utf-8"?>
<SlidingDrawer xmlns:android="http://schemas.android.com/apk/res/android"  
    android:id="@+id/drawer" 
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent" 
    android:handle="@+id/handle"  
    android:background="@drawable/a07"
    android:content="@+id/content">  
  
    <ImageView android:id="@id/handle" 
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content" 
        android:src="@drawable/arrow_up">
    </ImageView>  
    <ListView android:id="@id/content" 
        android:layout_width="fill_parent"  
        android:layout_height="fill_parent" 
        android:background="#ff00C0">
    </ListView>  
  
</SlidingDrawer>


In SlidingDrawerActivity implements OnItemClickListener, OnDrawerOpenListener and OnDrawerCloseListener as:
package com.imrankhanandroid.SlidingDrawerExp;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SlidingDrawer;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;

public class SlidingDrawerActivity extends Activity implements 
OnItemClickListener,OnDrawerOpenListener,OnDrawerCloseListener {
    private SlidingDrawer drawer;  
    private ImageView handle;  
    private ListView content;  
    private String[] strcntycode={"IN","US","UK","JAP","PK","CH"};
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Remove title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //Remove notification bar
        this.getWindow().setFlags(WindowManager.LayoutParams.
        FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
        drawer = (SlidingDrawer) this.findViewById(R.id.drawer);  
        handle = (ImageView) this.findViewById(R.id.handle);  
        content = (ListView) this.findViewById(R.id.content);  
        content.setAdapter(new ArrayAdapter(this,  
                android.R.layout.simple_list_item_1, strcntycode));
        content.setOnItemClickListener(this); 
        drawer.setOnDrawerOpenListener(this);  
        drawer.setOnDrawerCloseListener(this);  
    }

	@Override
	public void onItemClick(AdapterView arg0, 
                    View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
        Toast.makeText(this, "Clicked Position " + (arg2 + 1)+"Code is :"
        +strcntycode[arg2],Toast.LENGTH_SHORT).show();  
	}

	@Override
	public void onDrawerOpened() {
		// TODO Auto-generated method stub
		handle.setImageResource(R.drawable.arrow_down);
	}

	@Override
	public void onDrawerClosed() {
		// TODO Auto-generated method stub
		handle.setImageResource(R.drawable.arrow_up);
	}
}

Download Source Code: SlidingDrawerExample









Android ViewFlipper Example




STEP 1: Creating a new project from File->New->Android Project with ViewFlipperActivity Activity Name

STEP 2: Copy Image files to res/drawable Folder

STEP 3: In res/layout/main.xm layout add ViewFlipper as:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ViewFlipper  
        android:id="@+id/viewflipper"  
        android:layout_width="fill_parent"  
        android:layout_height="fill_parent"/>

</LinearLayout>


STEP 4: Create an anim folder inside res and put xml for Transaction effect for Left In, Right In,Left Out and Right Out.
res/anim/push_left_in.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate 
        android:fromXDelta="100%p" 
        android:toXDelta="0"  
        android:duration="500" />  
    <alpha 
        android:fromAlpha="0.1" 
        android:toAlpha="1.0"  
        android:duration="500" /> 
</set>

res/anim/push_left_out.xml:

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate 
        android:fromXDelta="0" 
        android:toXDelta="-100%p"  
        android:duration="500" />  
    <alpha 
        android:fromAlpha="1.0" 
        android:toAlpha="0.1"  
        android:duration="500" /> 
</set>

res/anim/push_right_in.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate 
      android:fromXDelta="-100%p" 
      android:toXDelta="0"  
      android:duration="500" />  
    <alpha 
        android:fromAlpha="0.1" 
        android:toAlpha="1.0"  
        android:duration="500" />  
</set>

res/anim/push_right_out.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">  
    <translate 
        android:fromXDelta="0" 
        android:toXDelta="100%p"  
        android:duration="500" />  
    <alpha 
        android:fromAlpha="1.0" 
        android:toAlpha="0.1"  
        android:duration="500" />  
</set>


STEP 5: In ViewFlipperActivity :
package com.imrankhanandroid.ViewFlipperExp;

import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ViewFlipper;

public class ViewFlipperActivity extends Activity implements  android.view.GestureDetector.OnGestureListener {
    /** Called when the activity is first created. */
    private int[] imageID = { 
    		R.drawable.a01, R.drawable.a02, 
    		R.drawable.a03, R.drawable.a04, 
    		R.drawable.a05, R.drawable.a06, 
    		R.drawable.a07, R.drawable.a08, 
    		R.drawable.a09, R.drawable.a010, 
    		R.drawable.a011
              };
    private ViewFlipper viewFlipper = null;  
    private GestureDetector gestureDetector = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Remove title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //Remove notification bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
        viewFlipper = (ViewFlipper) findViewById(R.id.viewflipper); 
        // gestureDetector Object is used to detect gesture events
        gestureDetector = new GestureDetector(this); 
        for (int i = 0; i < imageID.length; i++)  
        { 
            ImageView image = new ImageView(this);  
            image.setImageResource(imageID[i]);  
            image.setScaleType(ImageView.ScaleType.FIT_XY);
            viewFlipper.addView(image, new LayoutParams(  
                    LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        }
    }
	@Override
	public boolean onDown(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2,
			float arg3) {
		// TODO Auto-generated method stub
		if (arg0.getX() - arg1.getX() > 120)  
        {  
            
            this.viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this,  
                    R.anim.push_left_in));  
            this.viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,  
                    R.anim.push_left_out));  
            this.viewFlipper.showNext();  
            return true;  
        }
        else if (arg0.getX() - arg1.getX() < -120)  
        {  
            this.viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this,  
                    R.anim.push_right_in));  
            this.viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,  
                    R.anim.push_right_out));  
            this.viewFlipper.showPrevious();  
            return true;  
        }  
		return true;
	}
	@Override
	public void onLongPress(MotionEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
			float arg3) {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public void onShowPress(MotionEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public boolean onSingleTapUp(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}
    @Override  
    public boolean onTouchEvent(MotionEvent event)  
    {  
        return this.gestureDetector.onTouchEvent(event);  
    }
}

Download Source Code: ViewFlipperExample








Sunday, June 3, 2012

Android ImageSwitcher Example




STEP 1: Creating a new project from File->New->Android Project with ImageSwitcherExample Activity Name

STEP 2: Copy Image files to res/drawable Folder

STEP 3: In res/layout/main.xm layout add ImageSwitcher and Gallery View as:
<?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="fill_parent"
    android:orientation="vertical" >
    <ImageSwitcher 
        android:layout_width="fill_parent"  
        android:id="@+id/imgswitcher" 
        android:layout_height="fill_parent"  
        android:layout_alignParentTop="true" 
        android:layout_alignParentLeft="true" />    
    <Gallery android:id="@+id/galleryview" 
        android:layout_width="fill_parent"  
        android:layout_height="60dip" 
        android:background="#55000000"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentBottom="true" 
        android:gravity="center_vertical"  
        android:spacing="16dip" /> 
</RelativeLayout>

STEP 4: Create an ImageAdapter which extends BaseAdapter as:
package com.imrankhanandroid.Imageswitcherexp;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {

	private Context context;  
    public static Integer[] imageIDs={  
            R.drawable.a01,R.drawable.a02, 
            R.drawable.a03,R.drawable.a04, 
            R.drawable.a05,R.drawable.a06, 
            R.drawable.a07,R.drawable.a08, 
            R.drawable.a09,R.drawable.a010, 
            R.drawable.a011,R.drawable.a012, 
            R.drawable.a013
    };  
    public ImageAdapter(Context context){  
        this.context=context;  
    }  
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return imageIDs.length;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View 
			convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ImageView image=new ImageView(context);  
        image.setImageResource(imageIDs[position]);  
        image.setAdjustViewBounds(true);  
        image.setLayoutParams(new Gallery.LayoutParams(120,120));  
        image.setScaleType(ImageView.ScaleType.FIT_CENTER);  
        return image;  
	}

}

STEP 5: In ImageSwitcherExampleActivity implements ViewFactory and OnItemSelectedListener. as:
package com.imrankhanandroid.Imageswitcherexp;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ViewSwitcher.ViewFactory;

public class ImageSwitcherExampleActivity extends Activity 
    implements ViewFactory,OnItemSelectedListener {
    private ImageSwitcher mSwitcher;  
    private Gallery mGallery;  
    private int selectedTag = 0;  
    private int upX, downX;  
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Remove title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //Remove notification bar
        this.getWindow().setFlags(WindowManager.
        LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
        setTitle("ImageSwitcher Example");  
        mSwitcher = (ImageSwitcher) findViewById(R.id.imgswitcher);  
        mSwitcher.setFactory(ImageSwitcherExampleActivity.this);  
        mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,  
                android.R.anim.fade_in));  
        mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,  
                android.R.anim.fade_out));  
        mSwitcher.setOnTouchListener(touchlistener);  
        mGallery = (Gallery) findViewById(R.id.galleryview);  
        mGallery.setAdapter(new ImageAdapter(ImageSwitcherExampleActivity.this));  
        mGallery.setOnItemSelectedListener(this);  
       
    }
    OnTouchListener touchlistener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			if(event.getAction()==MotionEvent.ACTION_DOWN){
				downX=(int)event.getX();//Get Pressed Coordinates x
				return true;
			}
			else{
				if(event.getAction()==MotionEvent.ACTION_UP){
					upX=(int)event.getX();//get Released Coordinates x
					if(upX-downX>100){ //From left to right drag
						  //if this is first drag to to tail
						if(mGallery.getSelectedItemPosition()==0){
							selectedTag=mGallery.getCount()-1;
						}
						else
						{
							selectedTag=mGallery.getSelectedItemPosition()-1;
						}
					}
					else{
						  if(downX-upX>100){ //From right to left drag
							  if (mGallery.getSelectedItemPosition() == (mGallery  
			                            .getCount() - 1))  
			                        selectedTag = 0;  
			                    else  
			                        selectedTag = mGallery.getSelectedItemPosition() + 1;
						  }
					}
					return true;
				}
			}
			return false;
		} 
    	
    };
	@Override
	public View makeView() {
		// TODO Auto-generated method stub
		ImageView iv=new ImageView(this);
		iv.setBackgroundColor(0xFF000000);
		iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
		iv.setLayoutParams(new ImageSwitcher.LayoutParams(  
        LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); 
		return iv;
	}

	@Override
	public void onItemSelected(AdapterView arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		 mSwitcher.setImageResource(ImageAdapter.imageIDs[arg2]);  
	     selectedTag = arg2;  
	}

	@Override
	public void onNothingSelected(AdapterView arg0) {
		// TODO Auto-generated method stub
		
	}
}

Download Source Code: ImageSwitcherExample









Android Gallery Example

Gallery is an internal element which can scroll horizontally and layout component of the currently selected child elements are positioned in the center of it.



STEP 1: Creating a new project from File->New->Android Project with Gallerydemo Activity Name

STEP 2: Copy Image files to res/drawable Folder

STEP 3: In res/layout/main.xm layout add ImageView and Gallery View as:
 
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- ImageView for display image in background -->  
   <ImageView  
        android:id="@+id/imgview"  
        android:layout_width="fill_parent"  
        android:layout_height="fill_parent"  
        android:src="@drawable/a01"  
         /> 
         
         <!-- Gallery To show images Gallery  -->  
        <Gallery xmlns:android="http://schemas.android.com/apk/res/android"  
        android:id="@+id/galleryview"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:spacing="5dp"  
        /> 

</FrameLayout >

STEP 4: In res/values add attrs.xml as:
 
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <declare-styleable name="HelloGallery">  
        <attr name="android:galleryItemBackground"/>  
   </declare-styleable>
</resources>

STEP 5: In Gallerydemo Activity Create an ImageAdapter which extends BaseAdapter as:
package com.imrankhanandroid.Galleryexp;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Gallerydemo extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      //Remove title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
      //Remove notification bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
        
        final ImageView imagevew = (ImageView)findViewById(R.id.imgview);  
        Gallery gallryview = (Gallery)findViewById(R.id.galleryview); 
        gallryview.setAdapter(new ImageAdapter(this));
        gallryview.setOnItemClickListener(new OnItemClickListener() {

	@Override
	public void onItemClick(AdapterView parent,
            View view, int position,long id) {
		// TODO Auto-generated method stub
	        // The first few pictures show click 
		Toast.makeText(Gallerydemo.this, "" + position,  
		         Toast.LENGTH_LONG).show();  
		//Set the backgroundPart of theImageView
		imagevew.setImageResource(((ImageView) view).getId());
			}
		});
    }
    public class ImageAdapter extends BaseAdapter {

    	int mGalleryItemBackground;  
    	// Context object 
    	private Context mContext;  
    	// Picture array 
    	private Integer[] mImageIds ={
    			R.drawable.a01,R.drawable.a02,
    			R.drawable.a03,R.drawable.a04,
    			R.drawable.a05,R.drawable.a06,
    			R.drawable.a07,R.drawable.a08,
    			R.drawable.a09,R.drawable.a010,
    	};
    	// ImageAdapter Constructor 
    	public ImageAdapter(Context c) {
    	  this.mContext = c;
    	  //styleable resources
    	  TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
    	  mGalleryItemBackground = a.getResourceId(
    		R.styleable.HelloGallery_android_galleryItemBackground,0);
    		a.recycle();
    	}
    	// Get  number of items 
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mImageIds.length;  
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
		//Return  view 
		@Override
		public View getView(int position, View convertView, 
                   ViewGroup parent) {
			// TODO Auto-generated method stub
			ImageView iv = new ImageView(mContext); 
			iv.setImageResource(mImageIds[position]);
			iv.setId(mImageIds[position]);  
			iv.setLayoutParams(new Gallery.LayoutParams(120, 160));  
			iv.setScaleType(ImageView.ScaleType.FIT_XY);
			iv.setBackgroundResource(mGalleryItemBackground); 
			return iv;
		}
    }
    
}

Download Source Code: GalleryExample








Saturday, June 2, 2012

IntentService : Android


IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread - they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

IntentService is a subclass of Service, and can handle asynchronous requests (with Intent). Service can be started when needed, and a separate thread to handle each Intent to, but after processing will be canceled.

The work queue processor is generally used for the task from the application's main thread. All requests will be handled in a separate thread, but not blocking the main thread of the application. And time to process a request.

Service vs IntentService:

  • Service class uses the application’s main thread, while IntentService creates a worker thread and uses that thread to run the service.
  • IntentService creates a queue that passes one intent at a time to onHandleIntent(). Thus, implementing a multi-thread should be made by extending Service class directly.
  • Service class needs a manual stop using stopSelf(). Meanwhile, IntentService automatically stops itself when there is no intent in queue.
  • IntentService implements onBind() that returns null. This means that the IntentService can not be bound by default.
  • IntentService implements onStartCommand() that sends Intent to queue and to onHandleIntent().

Service vs Thread vs AsyncTask:

  • Threads or Async task perform their tasks in a background thread thus they do not block the main thread, while a service performs it’s work in the main thread. so if a service is performing an intensive task such as calling a web service, it may block the main thread until it finishes. So for intensive tasks a service should run it’s work in a background thread.
  • A service runs in the same process of the application and keeps running until stopped by itself, stopped by the user or killed by the system if it needs memory.

IntentService of example:
   In IntentServiceActivity.java: :


package com.imrankhanandroid.Intentserviceexp; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class IntentServiceActivity extends Activity { private TextView text; private Button btnStart; private Button btnSendOther; private MessageReceiver receiver ; // Action private static final String ACTION_RECV_MSG = "com.imrankhanandroid.intent.action.RECEIVE_MESSAGE"; private static final String ACTION_OTHER_MSG = "com.imrankhanandroid.intent.action.OTHER_MESSAGE"; // Message private static final String MESSAGE_IN="message_input"; private static final String MESSAGE_OUT="message_output"; // Called when the activity is first created. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); text=(TextView)findViewById(R.id.text); text.setText("Preparation"); btnStart=(Button)findViewById(R.id.btnStart); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent msgIntent = new Intent(IntentServiceActivity.this, IntentServicetest.class); text.setText(""); msgIntent.putExtra(MESSAGE_IN, text.getText().toString()); startService(msgIntent); } }); btnSendOther=(Button)findViewById(R.id.btnSendOther); btnSendOther.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub } }); //Dynamic registration Receiver IntentFilter filter = new IntentFilter(ACTION_RECV_MSG); filter.addCategory(Intent.CATEGORY_DEFAULT); receiver = new MessageReceiver(); registerReceiver(receiver, filter); IntentFilter filter2 = new IntentFilter(ACTION_OTHER_MSG); filter2.addCategory(Intent.CATEGORY_DEFAULT); receiver = new MessageReceiver(); registerReceiver(receiver, filter2); } //Broadcast to receive public class MessageReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String message = intent.getStringExtra(MESSAGE_OUT); text.setText(message); Toast.makeText(context, "message",Toast.LENGTH_SHORT).show(); } } }

   In IntentServicetest.java: :



package com.imrankhanandroid.Intentserviceexp; import android.app.IntentService; import android.content.Intent; import android.os.SystemClock; import android.text.format.DateFormat; import android.util.Log; // IntentService public class IntentServicetest extends IntentService { // Action private static final String ACTION_RECV_MSG = "com.imrankhanandroid.intent.action.RECEIVE_MESSAGE"; // Message private static final String MESSAGE_IN="message_input"; private static final String MESSAGE_OUT="message_output"; private final static String Tag="---IntentServicetest"; public IntentServicetest() { // TODO Auto-generated constructor stub super("IntentServicetest"); Log.d(Tag, "Constructor"); } @Override public void onDestroy() { Log.d(Tag, "onDestroy()"); super.onDestroy(); } @Override public void onStart(Intent intent, int startId) { Log.d(Tag, "onStart()"); super.onStart(intent, startId); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(Tag, "onStartCommand()"); return super.onStartCommand(intent, flags, startId); } @Override public void setIntentRedelivery(boolean enabled) { Log.d(Tag, "setIntentRedelivery()"); super.setIntentRedelivery(enabled); } @Override protected void onHandleIntent(Intent intent) { // TODO Auto-generated method stub Log.d(Tag, "IntentServicetest is onHandleIntent!"); String msgRecv = intent.getStringExtra(MESSAGE_IN); Log.d(Tag, msgRecv); for (int i = 0; i < 5; i++) { String resultTxt = msgRecv + " " + DateFormat.format("MM/dd/yy hh:mm:ss", System.currentTimeMillis()); Intent broadcastIntent = new Intent(); broadcastIntent.setAction(ACTION_RECV_MSG); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra(MESSAGE_OUT, resultTxt); sendBroadcast(broadcastIntent); SystemClock.sleep(1000); } } }

   In AndroidManifest.xml: :



<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.imrankhanandroid.Intentserviceexp" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="7" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:label="@string/app_name" android:name=".IntentServiceActivity" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".IntentServicetest"></service> </application> </manifest>




   In main.xml: :



<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="30sp" android:textColor="#FF0000" android:text="@string/hello" /> <Button android:id="@+id/btnStart" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Start" /> <Button android:id="@+id/btnSendOther" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="SendOtherBroadcast" /> </LinearLayout>
Download Source Code: IntentServiceExample








 
Powered by Blogger