Android App中使用Gallery制作幻燈片播放效果


http://www.jb51.net/article/83313.htm

我們有時候在iPhone手機上或者Windows上面看到動態的圖片,可以通過鼠標或者手指觸摸來移動它,產生動態的圖片滾動效果,還可以根據你的點擊或者觸摸觸發其他事件響應。同樣的,在Android中也提供這這種實現,這就是通過Gallery在UI上實現縮略圖瀏覽器。
我們來看看Gallery是如何來實現的,先把控件從布局文件中聲明,只需知道ID為gallery。

?
1
Gallery gallery = (Gallery) findViewById(R.id.gallery);

 一般情況下,我們在Android中要用到類似這種圖片容器的控件,都需要為它指定一個適配器,讓它可以把內容按照我們定義的方式來顯示,因此我們來給它加一個適配器,至於這個適配器如何實現,后面接着來操作,這里只需知道這個適配器的類叫

?
1
ImageAdapter。 gallery.setAdapter( new ImageAdapter( this ));

復制代碼接下來就是重頭戲了,適配器可以說是最重要的,我們來看看如何做?到這里似乎還缺少一些很重要的東西?什么東西呢?我們需要顯示的是圖片,那么圖片我們當然首先要准備好,這里我們准備了5張圖片(存放drawable文件夾中),我們用其IDs做索引,以便在適配器中使用。

?
1
2
3
4
5
6
7
private Integer[] mps = {
   R.drawable.icon1,
   R.drawable.icon2,
   R.drawable.icon3,
   R.drawable.icon4,
   R.drawable.icon5
};

OK,這里將開始定義適配器了,通過繼承BaseAdapter用以實現的適配器。 

?
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
public class ImageAdapter extends BaseAdapter {
  private Context mContext;
   public ImageAdapter(Context context) {
   mContext = context;
  }
  
  public int getCount() {
   return mps.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 image = new ImageView(mContext);
   image.setImageResource(mps[position]);
   image.setAdjustViewBounds( true );
   image.setLayoutParams( new Gallery.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
   return image;
  }
}

至此,整個Gallery基本都是先完成了,我們還需要為它添加一個監聽器,否則這個縮略圖瀏覽器就僅僅只可以看不能用了。

?
1
2
3
4
5
6
7
8
9
10
gallery.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() {
  @Override
  public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
  }
  
  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
  //這里不做響應
  }
});

一、效果圖展示

最近下載幾款手機應用研究了下,發了有些自定義控件驚人的相似,所以我覺得在以后的開發中,對一些控件的復用肯定是很多的,在首頁(非載入頁)一般都會有一個幻燈片效果,既可以放廣告也可以放推薦,如果圖片設計的好看,效果一般都會不錯,既然用到了Gallery,也附帶把相框效果的例子寫一寫(淘寶詳情界面的商品圖片滑動展示)

(1)幻燈片效果展示:

2016429144840422.jpg (482×284)

2016429144953428.jpg (482×282)

2016429145022604.jpg (482×284)

(2)商品圖片滑動展示

2016429145043263.jpg (480×199)

2016429145105549.jpg (480×199)

2016429145122886.jpg (480×198)

查看大圖:

2016429145136108.jpg (483×719)

 

二、部分代碼說明

1、幻燈片效果的實現:
自定義Gallery:DetailGallery.java
可視界面:ImgSwitchActivity.java
適配類:GalleryIndexAdapter.java
自定義Gallery主要重寫onFling通過按下和松手的位置不同比較是向右移動還是向左移動,部分代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {
  return e2.getX() > e1.getX();
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
   float velocityY) {
  int kEvent;
  if (isScrollingLeft(e1, e2)) {
   kEvent = KeyEvent.KEYCODE_DPAD_LEFT;
  } else {
   kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
  }
  onKeyDown(kEvent, null );
  return true ;
}

2、在適配類 GalleryIndexAdapter主要完成幻燈片的循環播放,在getCount里面返回值返回Integer.MAX_VALUE,然后在getView里面根據position與傳進來初始圖片個數進行余數計算得到每次循環到哪張圖片。部分代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Override
  public int getCount() {
   // TODO Auto-generated method stub
   return Integer.MAX_VALUE;
  }
  
  ……
  
  @Override
  public View getView( int position, View convertView, ViewGroup arg2) {
   // TODO Auto-generated method stub
   ImageView imageView = new ImageView(context);
   imageView.setBackgroundResource(imagList.get(position%imagList.size()));
   imageView.setScaleType(ScaleType.FIT_XY);
   imageView.setLayoutParams( new Gallery.LayoutParams(Gallery.LayoutParams.FILL_PARENT
     , Gallery.LayoutParams.WRAP_CONTENT));
   return imageView;
  }

     
3、在可視界面里面實現邏輯控制,通過定時器定時刷新幻燈片,定時器通過定時發送消息,消息接受處理機制接收到消息之后,就模擬滑動事件,調用Gallery的onFling方法實現圖片自動切換效果。選擇按鈕的顯示效果(RadioButton)需要在Gallery的setOnItemSelectedListener進行處理。 

?
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
//定時器和事件處理5秒刷新一次幻燈片
/** 展示圖控制器,實現展示圖切換 */
  final Handler handler_gallery = new Handler() {
   public void handleMessage(Message msg) {
    /* 自定義屏幕按下的動作 */
    MotionEvent e1 = MotionEvent.obtain(SystemClock.uptimeMillis(),
      SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,
      89.333336f, 265.33334f, 0);
    /* 自定義屏幕放開的動作 */
    MotionEvent e2 = MotionEvent.obtain(SystemClock.uptimeMillis(),
      SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN,
      300.0f, 238.00003f, 0);
     
    myGallery.onFling(e2, e1, -800, 0);
    /* 給gallery添加按下和放開的動作,實現自動滑動 */
    super.handleMessage(msg);
   }
  };
  protected void onResume() {
   autogallery();
   super.onResume();
  };
  private void autogallery() {
   /* 設置定時器,每5秒自動切換展示圖 */
   Timer time = new Timer();
   TimerTask task = new TimerTask() {
    @Override
    public void run() {
     Message m = new Message();
     handler_gallery.sendMessage(m);
    }
   };
   time.schedule(task, 8000, 5000);
  }
//指示按鈕和gallery初始化過程以及事件監聽添加過程
//初始化
  void init(){
   myGallery = (DetailGallery)findViewById(R.id.myGallery);
   gallery_points = (RadioGroup) this.findViewById(R.id.galleryRaidoGroup);
   ArrayList<Integer> list = new ArrayList<Integer>();
   list.add(R.drawable.banner1);
   list.add(R.drawable.banner2);
   list.add(R.drawable.banner3);
   list.add(R.drawable.banner4);
   GalleryIndexAdapter adapter = new GalleryIndexAdapter(list, context);
   myGallery.setAdapter(adapter);
   //設置小按鈕
   gallery_point = new RadioButton[list.size()];
   for (int i = 0; i < gallery_point.length; i++) {
    layout = (LinearLayout) inflater.inflate(R.layout.gallery_icon, null);
    gallery_point[i] = (RadioButton) layout.findViewById(R.id.gallery_radiobutton);
    gallery_point[i].setId(i);/* 設置指示圖按鈕ID */
    int wh = Tool.dp2px(context, 10);
    RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(wh, wh); // 設置指示圖大小
    gallery_point[i].setLayoutParams(layoutParams);
    layoutParams.setMargins(4, 0, 4, 0);// 設置指示圖margin值
    gallery_point[i].setClickable(false);/* 設置指示圖按鈕不能點擊 */
    layout.removeView(gallery_point[i]);//一個子視圖不能指定了多個父視圖
    gallery_points.addView(gallery_point[i]);/* 把已經初始化的指示圖動態添加到指示圖的RadioGroup中 */
   }
  }
  //添加事件
  void addEvn(){
   myGallery.setOnItemSelectedListener( new OnItemSelectedListener() {
  
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,
      int arg2, long arg3) {
     // TODO Auto-generated method stub
     gallery_points.check(gallery_point[arg2%gallery_point.length].getId());
    }
  
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
     // TODO Auto-generated method stub
      
    }
   });
  }

4、商品圖片滑動實現過程:
圖片滑動效果和上面的幻燈片效果非常的類似,只是在邏輯處理和界面上有一些小小的區別。
(1)適配器類GalleryAdapter.java上面進行了圖片縮放處理,節省了內存開銷,又可把圖片按照自己的要求縮放。

?
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
//由於是測試case,所以圖片都是寫死的為了區別,在position = 1的時候換了一張圖片
public View getView( int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    ImageView imageView = (ImageView) LayoutInflater.from(context).inflate(R.layout.img,
      null );
    Bitmap bitmap = null ;
    try {
     if (position == 1 ){
      bitmap = BitmapFactory.decodeStream(assetManager.open( "xpic11247_s.jpg" ));
      imageView.setTag( "xpic11247_s.jpg" );
     }
     else {
      bitmap = BitmapFactory.decodeStream(assetManager.open( "item0_pic.jpg" ));
      imageView.setTag( "item0_pic.jpg" );
     }
      
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    // 加載圖片之前進行縮放
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    float newHeight = 200 ;
    float newWidth = width*newHeight/height;
    float scaleWidth = (( float ) newWidth) / width;
    float scaleHeight = (( float ) newHeight) / height;
    // 取得想要縮放的matrix參數
    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);
    // 得到新的圖片
    Bitmap newbm = Bitmap.createBitmap(bitmap, 0 , 0 , width, height, matrix, true );
    System.out.println(newbm.getHeight()+ "-----------" +newbm.getWidth());
    imageView.setImageBitmap(newbm);
    // }
    return imageView;
  
   }

       
(2)添加了一個相框效果,如果圖片加載失敗,就會出現一個圖片壓縮之后大小相等的相框圖片。

?
1
2
3
4
5
6
7
8
<? xml version = "1.0" encoding = "utf-8" ?>
< ImageView xmlns:android = "http://schemas.android.com/apk/res/android"
  android:id = "@+id/waterfall_image"
  android:layout_width = "fill_parent"
  android:layout_height = "fill_parent"
  android:background = "@drawable/image_border"
  >
</ ImageView >

三、開發中遇到一些問題
1、

?
1
layout.removeView(gallery_point[i]); //一個子視圖不能指定了多個父視圖

如果需要把當前子childview添加到另外一個view里面去,則必須在當前的父View里面移除掉當前的childView,如果不進行這樣處理則會拋出Caused by: java.lang.IllegalStateException異常,提示The specified child already has a parent. You must call removeView() on the child's parent first.
2、在進行圖片縮放的時候,記得處理好dp和px直接的轉換。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM