Search...

Monday, November 14, 2011

How to send HttpClient request with timeout value in android



public static InputStream getGzipStreamWithTimeout(String url) throws Exception {
         
            InputStream instream=null;
         
            HttpParams my_httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(my_httpParams,5000);
        HttpConnectionParams.setSoTimeout(my_httpParams,5000);
        HttpClient httpClient = new DefaultHttpClient(my_httpParams);
         
            HttpUriRequest request = new HttpGet(url);
         

            try{
         
            HttpResponse response = httpClient.execute(request);
         
         

            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                  return null;
            }

            instream = response.getEntity().getContent();
         

            return instream;

      }

Sunday, November 13, 2011

How to delete border space around GridView in android

removing the selector with android:listSelector="@null” in gridview

How to Set margins in a LinearLayout programmatically in android


LayoutParams lp=new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(3,3,3,3);

How to disappear the list view divider in android


Override the below adapter method and return false.

Step1:

public class CustomAdapter extends BaseAdapter {
public boolean areAllItemsEnabled() {
return false;
}

public boolean areAllItemsSelectable() {
return false;
}

public boolean isEnabled(int position) {
return (false);
}

}

Step2: listView.setAdapter(new CustomAdapter() );


How to create popup window in android


This popup window will not stop the processing of other screen. You can set the popup location as well.
Example:


PopupWindow pw;
LayoutInflater  inflater=null;

public void showPopup(Activity context) {

try {

inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = inflater.inflate(R.layout.my_custom_popup_layout, null, false);

TextView f=(TextView)layout.findViewById(R.id.textview) ;
                        f.setText("Hello Android");
pw = new PopupWindow(layout, 400, LayoutParams.WRAP_CONTENT, true);
pw.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.my_bg));
pw.setOutsideTouchable(true);
pw.showAtLocation(context.findViewById(R.id.dvrBtn), Gravity.TOP,
395,65);
} catch (Exception e) {
e.printStackTrace();
}
}

How to make HttpDigest client authentication call in android


public void testDigest(){
         String url = "http://1.1.1.1:8080/mydata?client=0";
          String username = "test";
          String password = "test";
           
           
         try
       {
           AndroidHttpClient httpClient = AndroidHttpClient.newInstance("test digest");
         
           URL urlObj = new URL(url);
               HttpGet request = new HttpGet(url);
                 
                           HttpHost host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());
                       AuthScope scope = new AuthScope(urlObj.getHost(), urlObj.getPort());
                       UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);

                       CredentialsProvider cp = new BasicCredentialsProvider();
                       cp.setCredentials(scope, creds);
                       HttpContext credContext = new BasicHttpContext();
                       credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp);
                      
                       HttpResponse response = httpClient.execute(host,request,credContext);
                      
                       ByteArrayOutputStream v2 = new ByteArrayOutputStream();
                              response.getEntity().writeTo(v2);
                              System.out.println("----------------------------------------");
                              System.out.println(v2.toString());
                              System.out.println("----------------------------------------");
                              System.out.println(response.getStatusLine().getReasonPhrase());
                              System.out.println(response.getStatusLine().getStatusCode());
                       
                       
                  //}
          
         

         
           httpClient.close();
       }
       catch(Exception e){
           e.printStackTrace();
       }
   }
      

How to download image from url and convert to drawable in android


Pass the absolute path of the image location in the below method.
public static Drawable downloadImage(String loc) {

try {
URLConnection connection = new URL(loc).openConnection();
InputStream stream = connection.getInputStream();
BufferedInputStream in = new BufferedInputStream(stream);
ByteArrayOutputStream out = new ByteArrayOutputStream(50000);
int read;
byte[] b = new byte[50000];
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
out.flush();
out.close();
byte[] raw = out.toByteArray();
Drawable d = new BitmapDrawable(new ByteArrayInputStream(raw));

return d;
} catch (Exception e) {

return null;
}

How to group radio buttons in a custom adapter in android


Step1: Create one custom checkable class which extends Relative Layout and implements Checkable interface.

public class MyCustomCheckableView extends RelativeLayout implements Checkable{

 private boolean isChecked;
private List<Checkable> checkableViews;
 
 


 
   public MyCustomCheckableView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
initialise(attrs);
}

public MyCustomCheckableView(Context context, AttributeSet attrs) {
super(context, attrs);
initialise(attrs);
}

public MyCustomCheckableView(Context context, int checkableId) {
super(context);
initialise(null);
}


public boolean isChecked() {
return isChecked;
}

/*
* @see android.widget.Checkable#setChecked(boolean)
*/
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
for (Checkable c : checkableViews) {
c.setChecked(isChecked);
}
}

/*
* @see android.widget.Checkable#toggle()
*/
public void toggle() {
this.isChecked = !this.isChecked;
for (Checkable c : checkableViews) {
c.toggle();
}
}

@Override
protected void onFinishInflate() {
super.onFinishInflate();

final int childCount = this.getChildCount();
for (int i = 0; i < childCount; ++i) {
findCheckableChildren(this.getChildAt(i));
}
}

/**
* Read the custom XML attributes
*/
private void initialise(AttributeSet attrs) {
this.isChecked = false;
this.checkableViews = new ArrayList<Checkable>(5);
}

/**
* Add to our checkable list all the children of the view that implement the
* interface Checkable
*/
private void findCheckableChildren(View v) {
if (v instanceof Checkable) {
this.checkableViews.add((Checkable) v);
}

if (v instanceof ViewGroup) {
final ViewGroup vg = (ViewGroup) v;
final int childCount = vg.getChildCount();
for (int i = 0; i < childCount; ++i) {
findCheckableChildren(vg.getChildAt(i));
}
}

}

}

Step2: Create one layout xml and use the above checkable custom layout .
my_item.xml

<com.MyCustomCheckableView android:id="@+id/RelativeLayout001"
android:layout_width="fill_parent" android:layout_height="50dp"
xmlns:android="http://schemas.android.com/apk/res/android" android:background="#FFFFFF">


<TextView android:text="My Name" android:id="@+id/MyName"
android:singleLine="true" android:ellipsize="end"
android:layout_width="120dp" android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" android:gravity="left|center_vertical"
android:textAppearance="@style/sans20black" android:layout_marginLeft="10dp" android:focusable="false">
</TextView>

<RadioButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioButton" android:gravity="right|center_vertical"
android:layout_alignParentRight="true" android:focusable="false"/>

<TextView android:text="RceiverId" android:id="@+id/receiverId"
android:singleLine="true" android:ellipsize="end"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:gravity="right" android:paddingRight="20dp"
android:layout_below="@+id/MyName" android:layout_toRightOf="@+id/MyModel"
android:layout_alignParentRight="false"
android:layout_alignParentBottom="false" android:textAppearance="@style/sans13grey"
android:layout_marginRight="20dp" android:focusable="false">
</TextView>
<TextView android:layout_width="120dp" android:textStyle="normal"
android:singleLine="true" android:text="My Model" android:gravity="left|center_vertical"
android:ellipsize="end" android:layout_height="wrap_content"
android:id="@+id/MyModel" android:layout_below="@+id/MyName" android:focusable="false"
android:layout_alignParentLeft="true" android:layout_marginLeft="10dp" android:textAppearance="@style/sans13grey"></TextView>


</com.MyCustomCheckableView>


Step3 : In your activity set the following things in your list:
OnCreate(){
myList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
myList.setItemsCanFocus(false);
}

Step4 : Use the custom item XML created in step 2 in your custom adapter.
MyCustomAdapter.java
public View getView(int position, View convertView, ViewGroup parent) {

View row = convertView;
MyListView sView = null;
final String receiverId;


try {

if (row == null) {

row = inflater.inflate(R.layout. my_item.xml, null);
sView = (MyListView) new MyListView(row,_context);
row.setTag(sView);

} else {
sView = (MyListView) row.getTag();
}


                   


return row;

} catch (Exception e) {



return row;
}

}

How to set the custom background for currently selected and unselected gallery images in android


Step1: create two background images for selected and unselected images.
Step2: create new selector xml under drawable folder.
e.g:  gallery_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/unfocus"/>
<item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/focus"/>
<!-- Focused states -->
<item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/focus"/>
<item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/focus"/>
<!-- Pressed -->
<item android:state_pressed="true" android:drawable="@drawable/focus"/>
</selector>

Step3: Use this xml in your getView() method of your adapter.

public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);

i.setImageDrawable(galleyPhotos[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
80,70));
            i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(R.drawable. gallery_background);

return i;

How to use postDelayed() method in an application


If you wanted to give some pause on your operation and then execute some logic then postDelayed is the correct api for you.
Every view has the postDelayed api.

e.g:-

myView.postDelayed(new Runnable() {
public void run() {
myLayout.setVisibility(View.GONE);

}
}, 3000);

In this case, run method will be executed after 3 sec of delay.

How to change the background of actionbar in android


Step1: create three background image for action bar

Step2: create new style element in style.xml

<style name="actionBar" parent="android:style/Widget.Holo.ActionBar">
<item name="android:background">@drawable/bar_top_blue</item>
</style>

Step3: create new style element in style.xml to set “actionBar” style.

    <style name="CustomActionBar" parent="android:style/Theme.Holo">

<item name="android:actionBarStyle">@style/actionBar</item>

</style>
Step4: Use style element created in step3 in your activity attribute of AndroidManifest.xml

<activity android:name=".base.activity.MyActivity"
android:screenOrientation="sensorLandscape" android:theme="@style/CustomActionBar">



</activity>

How to change the default look and feel of checkbox in android


Step1 :Create two image for selected checkbox and un-selected checkbox.

Step2 : Use the below logic to make it work.

if (viewScoreCheck.isChecked()) {
   viewScoreCheck.setButtonDrawable(R.drawable.checkbox_select);
} else {
viewScoreCheck.setButtonDrawable(R.drawable.checkbox_idle);
}


How to change the Spinner item default look and feel in android


Step1: create new xml for your spinner item.

e.g: my_spinner_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="11dp"
    android:paddingBottom="11dp"
    android:paddingLeft="23dp" android:textAppearance="@style/sans17white">
</TextView>

Step2: Use your xml to create adapter for the spinner view.

ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(
this,R.layout.my_spinner_item, myOptions);
adapter.setDropDownViewResource(R.layout.my_spinner_item);

mySpinner.setAdapter(adapter);

How to change the tabs background color in actionbar in android


Step1 : create three background image (a)when tab is selected(b)when tab is in default state(c)when tab is focused.

Step2 : create selector xml under drawable folder.
e.g: actionbar_tabs_state_color.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/tab_default"/>
<item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/tab_selected"/>
<!-- Focused states -->
<item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/tab_focused"/>
<item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/tab_focused"/>
<!-- Pressed -->
<item android:state_pressed="true" android:drawable="@drawable/tab_focused"/>
</selector>

Step3: create new style element in style.xml

<style name="customActionBarTabStyle">
<item name="android:background">@drawable/actionbar_tabs_state_color</item>
<item name="android:paddingLeft">14dp</item>
<item name="android:paddingRight">14dp</item>

</style>

Step4 : create new style element in style.xml to set “customActionBarTabStyle” style.

<style name="CustomActionBar" parent="android:style/Theme.Holo">

<item name="android:actionBarTabStyle">@style/customActionBarTabStyle</item>


</style>

Step5: Use style element created in step4 in your activity attribute in AndroidManifest.xml

<activity android:name=".base.activity.MyActivity"
android:screenOrientation="sensorLandscape" android:theme="@style/CustomActionBar">



</activity>

How to Use multiple fragments in each screen in ViewPager in android


(1)Create layout which contain ViewPager.

e.g: my_pager.xml


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

    <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="0px"
            android:layout_weight="1">
    </android.support.v4.view.ViewPager>

</LinearLayout>

(2)Create layout where you are going to add your fragment.

e.g: my_container.xml

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

  <LinearLayout android:id="@+id/mod" android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent" >

       <FrameLayout android:id="@+id/Mod11" android:layout_width="331dp"
android:layout_height="589dp" android:layout_marginLeft="100dp" android:layout_marginTop="45dp" />

   <FrameLayout android:id="@+id/Mod22" android:layout_width="331dp"
android:layout_height="589dp" android:layout_marginLeft="10dp" android:layout_marginTop="45dp" />

<FrameLayout android:id="@+id/Mod33" android:layout_width="331dp"
android:layout_height="589dp" android:layout_marginLeft="10dp" android:layout_marginTop="45dp" />

   </LinearLayout>



</LinearLayout>


(3)create your activity class which will inflate your my_pager.xml and set adapter for your viewpager.


e.g: MyActivity.java


public class MyActivity extends Activity {

private ViewPager modulePager;
private static int NUM_PAGER_VIEWS = 3;


@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
           setContentView(R.layout. my_pager.xml)
            modulePager = (ViewPager) getView().findViewById(R.id.pager);
modulePager.setAdapter(new ModulePagerAdapter());

}


private class ModulePagerAdapter extends PagerAdapter {

@Override
public int getCount() {
return NUM_PAGER_VIEWS;
}


@Override
public Object instantiateItem(View collection, int position) {

View v  =getActivity().getLayoutInflater().inflate(
R.layout.my_container.xml, null);


FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();

if (position == 0) {


ft.add(R.id.Mod11, new HotFragment(), "a");

ft.add(R.id.Mod22, new WatchingFragment(),
"b");

ft.add(R.id.Mod33, new TodayFragment(), "c");

} else if (position == 1) {



ft.add(R.id.Mod11, new TodayFragment(), "d");

ft.add(R.id.Mod22, new WatchingFragment(),
"f");

ft.add(R.id.Mod33, new TodayFragment(), "g");

} else if (position == 2) {


ft.add(R.id.Mod11, new ModuleFragment(), "h");

ft.add(R.id.Mod22, new WatchingFragment(),
"i");

ft.add(R.id.Mod33, new ModuleFragment(), "j");

}

  ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();

((ViewPager) collection).addView(v, 0);

return v;
}

@Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((LinearLayout) view);
}

@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}

@Override
public void finishUpdate(View arg0) {
}

@Override
public Parcelable saveState() {
return null;
}

@Override
public void startUpdate(View arg0) {
}

@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
// TODO Auto-generated method stub

}

}

}


How to change the list item default look and feel in android


Step1: Create new xml for your list item.

e.g: my_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="11dp"
    android:paddingBottom="11dp"
    android:paddingLeft="23dp" android:textAppearance="@style/sans17white">
</TextView>

Step2: Use your xml to create adapter for the list view.

ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(
                        this,R.layout.my_list_item,myUtil.getCustommyCategory());

            myCategoryList.setAdapter(adapter);

How to catch global exception using Thread.UncaughtExceptionHandler interface


Step1 : create a class which implements Thread.UncaughtExceptionHandler
e.g: public class GlobalExceptionHandler implements
Thread.UncaughtExceptionHandler{
     
      public void uncaughtException(Thread thread, Throwable ex) {

            Log.d("GLOBAL EXCEPTION", "Exception :" + ex.toString()
                        + " and Message:" + ex.getMessage());
           
            ex.printStackTrace();

           
           

      }
     

}

Step2: Create a class which implements Application interface.
e.g: public class MyApplication extends Application.
      public MyApplication() {
            Thread.setDefaultUncaughtExceptionHandler(new             GlobalExceptionHandler());
       
      }
}

Step3: Update your AndroidManifest.xml with your application class.
e.g: <application android:label="MyProject" android:name="MyApplication">


So in this way all the unhandled exception will be caught by your GlobalExceptionHandler class.

How to dynamically add the fragment in the layout in android


Step1: create your layout and inflate in your activity onCreate() method.
e.g:sample_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent" android:layout_height="match_parent">

     
                 
  <FrameLayout android:id="@+id/sample"
                  android:layout_width="fill_parent" android:layout_height="fill_parent" android:visibility="visible"/>                             
                                               
      </>

</LinearLayout>

Step2 : Create your fragment class:

e.g: SampleFragment.java

public class SampleFragment extends Fragment{

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                  Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            return inflater.inflate(R.layout.sample_test, container, false);
      }



}


Step3: Put the below code in your activity.

FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction ft=null;

ft = fragmentManager.beginTransaction();

ft.replace(R.id.sample, new SampleFragment(),"Sample_Fragment");

ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();

So in this way you can dynamically add the fragment into your activity.

How to add custom layout in honeycomb ActionBar in android

Step1: Create your customview
e.g: sample_custom_layout.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="wrap_content">


      <Button android:visibility="visible" android:text=""
            android:id="@+id/button" android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingRight="10dp" android:paddingLeft="10dp"></Button>

</LinearLayout>

Step2 : Put the below code on your activity OnCreate() method
protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);


ActionBar bar= getActionBar();
View actionCustomView = getLayoutInflater().inflate(
                        R.layout. sample_custom_layout,null);
            bar.setCustomView(actionCustomView, new ActionBar.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                        Gravity.RIGHT));
           
            int change = bar.getDisplayOptions() ^ ActionBar.DISPLAY_SHOW_CUSTOM;
            bar.setDisplayOptions(change, ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_USE_LOGO);

}

How to use drag/flip on ImageSwitcher with Gallery View in android


Gallery and ImageSwitcher, in combination, we realize a simple browser image features.
Photo Gallery you can drag in addition to switching, I joined the setOnTouchListener events ImageSwitcher control to achieve, so ImageSwitcher switch can also drag images. This example is still using Java 's reflection mechanism to automatically read the resource in the picture.


Step1: Create layout with Gallery View and Image Switcher View.

<? Xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns: Android = " http://schemas.android.com/apk/res/android "
android: layout_width = "match_parent"
android: layout_height = "match_parent">
<ImageSwitcher android: id = "@ + id / switcher"
android: layout_width = "match_parent" android: layout_height = "match_parent" />
<Gallery android: id = "@ + id / gallery"
android: background = "# 55000000"
android: layout_width = "match_parent"
android: layout_alignParentBottom = "true"
android: layout_alignParentLeft = "true"
android: gravity = "center_vertical"
android: spacing = "16dp" android: layout_height = "100dp" />
</ RelativeLayout>



Step2: Use the following source code

Program source code is as follows:
view plaincopy to clipboardprint?
package com.testImageView;
import java.lang.reflect.Field;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery.LayoutParams;
import android.widget.ViewSwitcher.ViewFactory;
public class testImageView extends Activity implements ViewFactory {
private ImageSwitcher is;
private Gallery gallery;
private int downX, upX;
private ArrayList <Integer> imgList = new ArrayList <Integer> ();// Image ID
@ Override
protected void onCreate (Bundle savedInstanceState) {
/ / TODO Auto-generated method stub
super.onCreate (savedInstanceState);
setContentView (R.layout.main);
/ / Use reflection to obtain a picture ID resources
Field [] fields = R.drawable.class.getDeclaredFields ();
for (Field field: fields)
{
if (! "icon". equals (field.getName ()))// pictures outside apart from icon
{
int index = 0;
try {
index = field.getInt (R.drawable.class);
} Catch (IllegalArgumentException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
} Catch (IllegalAccessException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
}
/ / Save the image ID
imgList.add (index);
}
}
/ / Set ImageSwitcher control
is = (ImageSwitcher) findViewById (R.id.switcher);
is.setFactory (this);
is.setInAnimation (AnimationUtils.loadAnimation (this,
android.R.anim.fade_in));
is.setOutAnimation (AnimationUtils.loadAnimation (this,
android.R.anim.fade_out));
is.setOnTouchListener (new OnTouchListener () {
/ *
* In ImageSwitcher can switch on the control slide image
* /
@ Override
public boolean onTouch (View v, MotionEvent event) {
if (event.getAction () == MotionEvent.ACTION_DOWN)
{
downX = (int) event.getX ();// get the coordinates when pressed
return true;
}
else if (event.getAction () == MotionEvent.ACTION_UP)
{
upX = (int) event.getX ();// get the coordinates when released
int index = 0;
if (upX-downX> 100) / / left onto the right, ie, on the one before
{
/ / If this is the first, then go to the tail
if (gallery.getSelectedItemPosition () == 0)
index = gallery.getCount () -1;
else
index = gallery.getSelectedItemPosition () -1;
}
else if (downX-upX> 100) / / right onto the left, that is, after watching a
{
/ / If this is the last, then go to the first
if (gallery.getSelectedItemPosition ()==( gallery.getCount () -1))
index = 0;
else
index = gallery.getSelectedItemPosition () +1;
}
/ / Change the gallery image selected, automatically triggering the setOnItemSelectedListener ImageSwitcher
gallery.setSelection (index, true);
return true;
}
return false;
}
});
/ / Set the gallery control
gallery = (Gallery) findViewById (R.id.gallery);
gallery.setAdapter (new ImageAdapter (this));
gallery.setOnItemSelectedListener (new OnItemSelectedListener () {
@ Override
public void onItemSelected (AdapterView <?> arg0, View arg1,
int position, long arg3) {
is.setImageResource (imgList.get (position));
}
@ Override
public void onNothingSelected (AdapterView <?> arg0) {
/ / TODO Auto-generated method stub
}
});
}
/ / Set ImgaeSwitcher
@ Override
public View makeView () {
ImageView i = new ImageView (this);
i.setBackgroundColor (0xFF000000);
i.setScaleType (ImageView.ScaleType.CENTER); / / center
i.setLayoutParams (new ImageSwitcher.LayoutParams (/ / adaptive image size
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return i;
}
public class ImageAdapter extends BaseAdapter {
public ImageAdapter (Context c) {
mContext = c;
}
public int getCount () {
return imgList.size ();
}
public Object getItem (int position) {
return position;
}
public long getItemId (int position) {
return position;
}
public View getView (int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView (mContext);
i.setImageResource (imgList.get (position));
i.setAdjustViewBounds (true);
i.setLayoutParams (new Gallery.LayoutParams (
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
return i;
}
private Context mContext;
}
}