Pages

Showing posts with label HelloGallery. Show all posts
Showing posts with label HelloGallery. Show all posts

Monday, July 23, 2012

Creating a custom Sliding GalleryView with Paging in android

This is a simple example showing A sliding Gallery in android. This example shows a sliding gallery with a paging Control and a changing page text which also indicate the page change.
Create a new project named “SlidingGallery” and copy this code into “SlidingGalleryDemo.java“.
My Activity name is “SlidingGalleryDemo.java” here

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package com.coderzheaven.pack;
 
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
 
public class SlidingGalleryDemo extends Activity {
     
    Gallery ga;
    int width, height;
    LinearLayout linear;
    LinearLayout layout;
    Integer[] pics = {
            R.drawable.android_1,
            R.drawable.android_2,
            R.drawable.android_3,
            R.drawable.android_4,
            R.drawable.android_5  
    };
    ImageView paging;
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.threemenu);
          
         layout = (LinearLayout) findViewById(R.id.imageLayout1);
             
         DisplayMetrics displaymetrics = new DisplayMetrics();
         getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
         width = displaymetrics.heightPixels;
         height = displaymetrics.widthPixels;
             
         for(int i=0; i<pics.length; i++)
         {
            paging = new ImageView(this);
            paging.setId(i);
            paging.setBackgroundResource(R.drawable.unsel);
            layout.addView(paging);
         }
          
         ga = (Gallery)findViewById(R.id.thisgallery);
         ga.setAdapter(new ImageAdapter(this));
          
         ga.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
                {                  
                    System.out.println("SELECTED : " + arg2);
                }              
            });
    }
 
    public class ImageAdapter extends BaseAdapter {
 
        private Context ctx;
        int imageBackground;
        int pre=-1;
        public ImageAdapter(Context c) {
            ctx = c;
        }
 
        public int getCount() {
             
            return pics.length;
        }
 
        public View getView(int arg0, View convertView, ViewGroup arg2) {
 
             ImageView iv;
             LinearLayout layoutnew = new LinearLayout(getApplicationContext());           
             layoutnew.setOrientation(LinearLayout.VERTICAL);
                 
             if (convertView == null)
             {
                iv = new ImageView(ctx);
                iv.setImageResource(pics[arg0]);
                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                int temp =(int) (height/1.7f);
                int temp_y = (int) ((3*temp)/2.0f);
                iv.setLayoutParams(new Gallery.LayoutParams(temp,temp_y));
                iv.setBackgroundResource(imageBackground);
             }
             else
             {
                iv = (ImageView) convertView;
             }
             TextView tv = new TextView(ctx);
             tv.setText("Page " + (arg0+1));
             tv.setTextColor(0xFFFFFFFF);
             tv.setPadding(0, 15, 0, 0);
             tv.setTextSize(18);
             tv.setGravity(Gravity.CENTER);
             layoutnew.addView(iv);
             layoutnew.addView(tv);
             
            return layoutnew;
        }
 
        @Override
        public Object getItem(int position) {
            return null;
        }
 
        @Override
        public long getItemId(int position) {
            if(pre !=-1)
            {
                ImageView img = (ImageView) findViewById(pre);
                img.setBackgroundResource(R.drawable.unsel);
            }
            ImageView img1 = (ImageView) findViewById(position);
            img1.setBackgroundResource(R.drawable.sel);
            this.pre = position;
            return position;
        }
    }
}
Now create a new class and name it “GalleryCustom.java” which extends “Gallery” and copy this code into it.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.coderzheaven.pack;
 
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Gallery;
 
public class GalleryCustom extends Gallery {
 
    public GalleryCustom(Context ctx, AttributeSet attrSet)
    {
        super(ctx,attrSet);
    }
 
    @SuppressWarnings("unused")
    private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2)
    {
           return e2.getX() > e1.getX();
    }
 
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY){
      return true
    }
}
Now we will create the layout for the page. Copy this code to the main.xml.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?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:keepScreenOn="true" 
    android:background="@drawable/Hotpink">
     
    <LinearLayout
        android:layout_width="fill_parent"
        android:id="@+id/imageLayout1"
        android:layout_marginBottom="5dip"
        android:layout_alignParentBottom="true"
        android:gravity="center_horizontal|center_vertical"
        android:orientation="horizontal"
        android:layout_height="wrap_content"
     </LinearLayout>
      
    <LinearLayout
        android:layout_width="fill_parent"
        android:id="@+id/imageLayout"
        android:gravity="center"
        android:layout_alignParentTop="true"
        android:layout_above="@+id/imageLayout"
        android:layout_height="fill_parent" >
     
        <com.coderzheaven.pack.GalleryCustom
            android:id="@+id/thisgallery"
            android:spacing="60dip"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
             
    </LinearLayout>
     
</RelativeLayout>
OK Its done. Now run the project and see the result.
Gallery 1
Gallery 1
Gallery 1
Gallery 1
Gallery 1

Tuesday, May 24, 2011

hHelloGallery, get and display the path of selected picture

Further extend from previouse exercise, HelloGallery, read picture files from SD, using File ArrayList, and File type checking for HelloGallery, the path of the selected picture will be displayed using Toast.



It involve little bit modification on onItemClick(AdapterView parent, View v, int position, long id), and also onCreate(Bundle savedInstanceState).


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

Gallery g = (Gallery) findViewById(R.id.gallery);

  final List<String> SD = ReadSDCard();
  g.setAdapter(new ImageAdapter(this, SD));
    
  g.setOnItemClickListener(new OnItemClickListener()
 {
      public void onItemClick(AdapterView<?> parent,
           View v, int position, long id) {
         Toast.makeText(HelloGallery.this,
    (CharSequence)SD.get(position),
    Toast.LENGTH_LONG).show();
      }
  });
}

File type checking for HelloGallery

In the previous article, HelloGallery, read picture files from SD, using File ArrayList, the application view all files, no matter what type it is. Here, add a conditional checking for file type, by checking on the extension. Only files with extension jpg, gif and png will be added in the File ArrayList. Such change involve modification of the method ReadSDCard() only.


private List<String> ReadSDCard()
{
List<String> tFileList = new ArrayList<String>();

//It have to be matched with the directory in SDCard
 File f = new File("/sdcard/pictures/");

 File[] files=f.listFiles();

 for(int i=0; i<files.length; i++)
 {
  File file = files[i];

     String curFile=file.getPath();
     String ext=curFile.substring(curFile.lastIndexOf(".")+1, 
       curFile.length()).toLowerCase();
     if(ext.equals("jpg")||ext.equals("gif")||ext.equals("png"))
   tFileList.add(file.getPath());
 }

 return tFileList;
}

HelloGallery, read picture files from SD, using File ArrayList

It extend from previous exercise, HelloGallery, using Gallery Widget, but read files from SD instead of R.drawable.



Firstly, you have to Create an SD Card to existing AVD and Copying Files to a Disk Image.

All the xml files are same as previous, just keep it no change.

Modify the HelloGallery.java:

package com.exercise.HelloGallery;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

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

    Gallery g = (Gallery) findViewById(R.id.gallery);
    g.setAdapter(new ImageAdapter(this, ReadSDCard()));

    g.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent,
          View v, int position, long id) {
        }
    });
}

private List<String> ReadSDCard()
{
 List<String> tFileList = new ArrayList<String>();

 //It have to be matched with the directory in SDCard
 File f = new File("/sdcard/pictures/");

 File[] files=f.listFiles();

 for(int i=0; i<files.length; i++)
 {
  File file = files[i];
  /*It's assumed that all file in the path
    are in supported type*/
  tFileList.add(file.getPath());
 }

 return tFileList;
}

public class ImageAdapter extends BaseAdapter {
    int mGalleryItemBackground;
    private Context mContext;
    private List<String> FileList;

    public ImageAdapter(Context c, List<String> fList) {
        mContext = c;
        FileList = fList;
        TypedArray a = obtainStyledAttributes(R.styleable.Theme);
        mGalleryItemBackground = a.getResourceId(
          R.styleable.Theme_android_galleryItemBackground,
          0);
        a.recycle();
    }

    public int getCount() {
        return FileList.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);

        Bitmap bm = BitmapFactory.decodeFile(
          FileList.get(position).toString());
        i.setImageBitmap(bm);
    
        i.setLayoutParams(new Gallery.LayoutParams(150, 100));
        i.setScaleType(ImageView.ScaleType.FIT_XY);
        i.setBackgroundResource(mGalleryItemBackground);
    
        return i;
    }
}
}

Friday, May 20, 2011

HelloGallery, read picture files from SD, using File ArrayList

It extend from previous exercise, HelloGallery, using Gallery Widget, but read files from SD instead of R.drawable.



Firstly, you have to Create an SD Card to existing AVD and Copying Files to a Disk Image.

All the xml files are same as previous, just keep it no change.

Modify the HelloGallery.java:

package com.exercise.HelloGallery;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

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

    Gallery g = (Gallery) findViewById(R.id.gallery);
    g.setAdapter(new ImageAdapter(this, ReadSDCard()));

    g.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent,
          View v, int position, long id) {
        }
    });
}

private List<String> ReadSDCard()
{
 List<String> tFileList = new ArrayList<String>();

 //It have to be matched with the directory in SDCard
 File f = new File("/sdcard/pictures/");

 File[] files=f.listFiles();

 for(int i=0; i<files.length; i++)
 {
  File file = files[i];
  /*It's assumed that all file in the path
    are in supported type*/
  tFileList.add(file.getPath());
 }

 return tFileList;
}

public class ImageAdapter extends BaseAdapter {
    int mGalleryItemBackground;
    private Context mContext;
    private List<String> FileList;

    public ImageAdapter(Context c, List<String> fList) {
        mContext = c;
        FileList = fList;
        TypedArray a = obtainStyledAttributes(R.styleable.Theme);
        mGalleryItemBackground = a.getResourceId(
          R.styleable.Theme_android_galleryItemBackground,
          0);
        a.recycle();
    }

    public int getCount() {
        return FileList.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);

        Bitmap bm = BitmapFactory.decodeFile(
          FileList.get(position).toString());
        i.setImageBitmap(bm);
    
        i.setLayoutParams(new Gallery.LayoutParams(150, 100));
        i.setScaleType(ImageView.ScaleType.FIT_XY);
        i.setBackgroundResource(mGalleryItemBackground);
    
        return i;
    }
}
}

HelloGallery, using Gallery Widget.

Here is a exercise to implement a picture view using Gallery, a view that shows items in a center-locked, horizontally scrolling list.



Basically, this exercise follow the Android Tutorial, Hello Gallery. But in my practice, error is complained in building. I have to create a attrs.xml and modify some code to fix it.

Here is how I fix it to make it work.

Create a Android Application, HelloGallery. Copy some images, in .png format, into res/drawable/ directory. Named image_01..05.png in my case.

Android supports bitmap resource files in a few different formats: png (preferred), jpg (acceptable), gif (discouraged). The bitmap file itself is compiled and referenced by the file name without the extension (so res/drawable/my_picture.png would be referenced as R.drawable.my_picture).

Create res/values/attrs.xml to define Theme_android_galleryItemBackground.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Theme">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>


Modify main.xml to have a Gallery in the screen.
<?xml version="1.0" encoding="utf-8"?>
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>


Finally, modify the HelloGallery.java
package com.exercise.HelloGallery;

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.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 HelloGallery extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   Gallery g = (Gallery) findViewById(R.id.gallery);
   g.setAdapter(new ImageAdapter(this));

   g.setOnItemClickListener(new OnItemClickListener() {
       public void onItemClick(AdapterView<?> parent,
           View v, int position, long id) {
           Toast.makeText(HelloGallery.this, "" + position,
               Toast.LENGTH_SHORT).show();
       }
   });
}

public class ImageAdapter extends BaseAdapter {
   int mGalleryItemBackground;
   private Context mContext;

   private Integer[] mImageIds = {
           R.drawable.image_01,
           R.drawable.image_02,
           R.drawable.image_03,
           R.drawable.image_04,
           R.drawable.image_05
   };

   public ImageAdapter(Context c) {
       mContext = c;
       TypedArray a = obtainStyledAttributes(R.styleable.Theme);
       mGalleryItemBackground = a.getResourceId(
         R.styleable.Theme_android_galleryItemBackground,
                   0);
       a.recycle();
   }

   public int getCount() {
       return mImageIds.length;
   }

   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(mImageIds[position]);
       i.setLayoutParams(new Gallery.LayoutParams(150, 100));
       i.setScaleType(ImageView.ScaleType.FIT_XY);
       i.setBackgroundResource(mGalleryItemBackground);

       return i;
   }
}
}

Popular Posts