Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 GridView 搭配 ImageSwitcher 動手做一個電子相簿

編輯:關於 Android 程式設計

打開手機相簿,你看到的通常是這樣的流程:先是一整片網格狀的縮圖牆,點其中一張後進入全屏檢視,再用手指左右滑動切換上一張、下一張。這個看似理所當然的互動,用 Android 原生的 GridView 加 ImageSwitcher 就能做出來,而且程式碼量比想像中少很多。

先說資料傳遞:Intent 是你的朋友

從縮圖牆跳到全屏檢視時,需要把「使用者點了第幾張」這個資訊帶過去,做法是 Intent.putExtra() 送出、getIntExtra() 接收。關於 Intent 的完整用法,之後會有專文深入說明。

第一步:首頁的 GridView 版面(grid_layout.xml)

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

     <GridView
         android:id="@+id/gv"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:numColumns="auto_fit"
         android:verticalSpacing="10dp"
         android:gravity="center"
         android:horizontalSpacing="10dp"></GridView>
 </LinearLayout>

第二步:單一格子的版面(griditem_layout.xml)

這裡的關鍵是 adjustViewBounds 加上 maxWidth / maxHeight。實際專案請依你的圖片尺寸與目標機型解析度調整,讓縮圖等比例縮放,不然很容易出現變形或排版跑掉的情況。

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
     xmlns:app="https://schemas.android.com/apk/res-auto"
     android:orientation="vertical"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:gravity="center">

     <ImageView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:adjustViewBounds="true"
         android:maxWidth="280dp"
         android:maxHeight="280dp"
         android:src="@mipmap/a1"
         android:id="@+id/imageView" />
 </LinearLayout>

第三步:全屏檢視畫面(activity_main.xml)

主容器用 FrameLayout 做層疊,切換的動畫交給 ImageSwitcher,底部的導航小圓點則用一列 LinearLayout 排一排 ImageView。圓點數量對應照片張數,實務上比較好的做法是用程式動態產生,而不是寫死在版面檔裡。

 <?xml version="1.0" encoding="utf-8"?>
 <FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
     xmlns:tools="https://schemas.android.com/tools"
     android:id="@+id/activity_main"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:context="com.example.administrator.switcher.MainActivity">

     <ImageSwitcher
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:id="@+id/is">
     </ImageSwitcher>

     <LinearLayout
         android:id="@+id/point_layout"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_gravity="bottom"
         android:orientation="horizontal">
         <ImageView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@mipmap/default_holo"/>
         <ImageView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@mipmap/default_holo"/>
         <ImageView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@mipmap/default_holo"/>
         <ImageView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@mipmap/default_holo"/>
     </LinearLayout>
 </FrameLayout>

第四步:縮圖牆的 Activity(GridActivity.java)

自訂 Adapter 繼承 BaseAdapter,並在 getView() 裡用 ViewHolder 模式快取子 View 參照,這是列表效能最基本的優化手段。

 import android.content.Intent;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.AdapterView;
 import android.widget.BaseAdapter;
 import android.widget.GridView;
 import android.widget.ImageView;

 public class GridActivity extends AppCompatActivity {

     private GridView gv;
     int[] images = { R.mipmap.a1, R.mipmap.a2, R.mipmap.a3, R.mipmap.a4 };

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.grid_layout);
         gv = (GridView) findViewById(R.id.gv);
         gv.setAdapter(new MyAdapter());

         // 每個格子的點擊事件
         gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
             @Override
             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                 // 建立要跳轉的 Intent
                 Intent intent = new Intent(GridActivity.this, MainActivity.class);
                 // 把點擊的位置(下標)放進 Intent,用於 Activity 間的資料傳遞
                 intent.putExtra("select", position);
                 startActivity(intent);
             }
         });
     }

     class MyAdapter extends BaseAdapter {
         @Override
         public int getCount() {
             return images.length;
         }

         @Override
         public Object getItem(int position) {
             return images[position];
         }

         @Override
         public long getItemId(int position) {
             return position;
         }

         @Override
         public View getView(int position, View convertView, ViewGroup parent) {
             ViewHolder vh;
             if (convertView == null) {
                 convertView = getLayoutInflater().inflate(R.layout.griditem_layout, null);
                 vh = new ViewHolder();
                 vh.iv = (ImageView) convertView.findViewById(R.id.imageView);
                 convertView.setTag(vh);
             }
             vh = (ViewHolder) convertView.getTag();
             vh.iv.setImageResource(images[position]);
             return convertView;
         }

         class ViewHolder {
             ImageView iv;
         }
     }
 }

第五步:全屏檢視的 Activity(MainActivity.java)

這裡有幾個值得注意的設計:

  • 實作 ViewSwitcher.ViewFactory,由 makeView() 提供 ImageSwitcher 內部切換用的 ImageView。
  • 用 startX / endX 記錄手指按下與放開的 X 座標,位移超過 30 才算一次有效滑動,避免誤觸。
  • 用三元運算處理環狀切換:到底了就回到第一張,到頭了就跳到最後一張。
 import android.content.Intent;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.view.MotionEvent;
 import android.view.View;
 import android.widget.ImageSwitcher;
 import android.widget.ImageView;
 import android.widget.LinearLayout;
 import android.widget.ViewSwitcher;

 import java.util.ArrayList;

 public class MainActivity extends AppCompatActivity
         implements ViewSwitcher.ViewFactory, View.OnTouchListener {

     private ImageSwitcher is;          // 切換用的 ImageSwitcher
     private LinearLayout point_layout; // 導航圓點的容器

     // 圖片資源,順序必須與 GridActivity 中一致
     int[] images = { R.mipmap.a1, R.mipmap.a2, R.mipmap.a3, R.mipmap.a4 };

     ArrayList<ImageView> points = new ArrayList<>(); // 存放所有導航圓點
     int index;      // 目前顯示的圖片下標
     float startX;   // 手指按下時的 X 座標
     float endX;     // 手指離開時的 X 座標

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         // 接收 GridActivity 傳來的下標
         Intent intent = getIntent();
         index = intent.getIntExtra("select", 0);

         is = (ImageSwitcher) findViewById(R.id.is);
         is.setFactory(this);   // 透過 Factory 提供切換用的 ImageView
         initpoint();
         is.setOnTouchListener(this);
     }

     // 初始化導航圓點
     private void initpoint() {
         point_layout = (LinearLayout) findViewById(R.id.point_layout);
         int count = point_layout.getChildCount(); // 取得版面中的圓點數量
         for (int i = 0; i < count; i++) {
             points.add((ImageView) point_layout.getChildAt(i));
         }
         // 把對應目前圖片的圓點設為實心狀態
         points.get(index).setImageResource(R.mipmap.touched_holo);
     }

     // 依目前選中的圖片切換圓點狀態
     public void setImageBackground(int selectImage) {
         for (int i = 0; i < points.size(); i++) {
             if (i == selectImage) {
                 points.get(i).setImageResource(R.mipmap.touched_holo);
             } else {
                 points.get(i).setImageResource(R.mipmap.default_holo);
             }
         }
     }

     // ViewFactory 的方法:實例化切換用的 ImageView
     @Override
     public View makeView() {
         ImageView iv = new ImageView(this);
         iv.setScaleType(ImageView.ScaleType.FIT_XY);
         iv.setImageResource(images[index]); // 第一個顯示的就是跳轉過來的那張
         return iv;
     }

     @Override
     public boolean onTouch(View v, MotionEvent event) {
         if (event.getAction() == MotionEvent.ACTION_DOWN) {
             startX = event.getX();
         } else if (event.getAction() == MotionEvent.ACTION_UP) {
             endX = event.getX();

             if (startX - endX > 30) {
                 // 左滑 → 下一張, Already at the end 就回到開頭
                 index = index + 1 < images.length ? ++index : 0;
                 is.setInAnimation(this, android.R.anim.fade_in);
                 is.setOutAnimation(this, android.R.anim.fade_out);
             } else if (endX - startX > 30) {
                 // 右滑 → 上一張, Already at the first 就跳到最後
                 index = index - 1 >= 0 ? --index : images.length - 1;
                 is.setInAnimation(this, android.R.anim.fade_in);
                 is.setOutAnimation(this, android.R.anim.fade_out);
             }

             is.setImageResource(images[index]);
             setImageBackground(index);
         }
         return true;
     }
 }

整套流程走完,你就有了一個能用的迷你相簿。想再進一步的話,可以把照片來源換成 ContentResolver 查詢 MediaStore 的實際相簿內容,並用 Glide 或 Picasso 取代 setImageResource,才能處理大圖的記憶體問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved