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

從縮圖牆跳到全屏檢視時,需要把「使用者點了第幾張」這個資訊帶過去,做法是 Intent.putExtra() 送出、getIntExtra() 接收。關於 Intent 的完整用法,之後會有專文深入說明。
<?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>
這裡的關鍵是 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>
主容器用 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>
自訂 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;
}
}
}
這裡有幾個值得注意的設計:
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,才能處理大圖的記憶體問題。
Android View 源碼剖析:requestLayout、invalidate 與 postInvalidate 的差異
requestLayout:請求重新布局當 View 的大小、位置或可見狀態可能改變時,可以呼叫 requestLayout。它會從目前 View 開始,沿著父容器層層向
Android 學習筆記二十:Toast 吐司、Notification 通知與 PopupWindow 彈出視窗
Toast 吐司 Toast 是我們日常開發中經常使用的元件。它是 Android 系統用來顯示訊息的一種機制,與 Dialog 不同,Toast 不會取得焦點,通常在顯
Android 接入微信支付踩坑實錄:從統一下單到成功拉起支付
前言 動手之前,「微信支付是個坑」這句話已經聽過很多次,心裡多少有底。結果一路走來確實波折,但最終還是調通了。以下把整個流程與踩過的雷完整記錄下來,希望讓你少走幾趟彎路。
用程式碼安裝與卸載 Android APK 的完整實作
想在自己的 App 裡做「安裝」與「卸載」按鈕,靠的是 Intent 加上正確的 action 與 data。核心關鍵在這一行: intent.setDataAndTyp