編輯:關於 Android 程式設計
我們常在 iPhone 或 Windows 上看到可透過滑鼠或手指拖動、產生動態滾動效果的圖片瀏覽。同樣地,Android 透過 Gallery 控制項也能實現這種縮略圖瀏覽器效果。本文將從基礎用法講到幻燈片與商品圖滑動兩個實戰案例。
首先在布局中聲明 Gallery 控制項並獲取物件:
Gallery gallery = (Gallery) findViewById(R.id.gallery);
由於 Gallery 這類圖片容器需要透過適配器來決定顯示方式,因此為它指定一個 ImageAdapter:
gallery.setAdapter(new ImageAdapter(this));
顯示的圖片需事先準備好,這裡準備了 5 張放在 drawable 中的圖片,並以 ID 陣列做索引:
private Integer[] mps = { R.drawable.icon1, R.drawable.icon2, R.drawable.icon3, R.drawable.icon4, R.drawable.icon5 };
接著定義繼承自 BaseAdapter 的 ImageAdapter:
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 添加監聽器,否則它就只是「只能看不能用」:
gallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View v,int position, long id) { } @Override public void onNothingSelected(AdapterView<?> arg0) { //這裡不做響應 } });
在實際應用中,首頁通常會有一個幻燈片效果,既可放廣告也可放推薦;此外還實現了類似淘寶詳情的商品圖片滑動展示。
(1)幻燈片效果展示:



(2)商品圖片滑動展示:



查看大圖:

1、幻燈片效果的實現:
自訂 Gallery(DetailGallery.java)主要重寫 onFling,透過比較按下與松手的位置判斷是向右還是向左移動:
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 與初始圖片數量取餘數,計算每次循環到哪張圖片。
@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)的顯示效果則在 setOnItemSelectedListener 中處理。
//定時器和事件處理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 中對圖片進行縮放處理,既節省內存開銷,又能自訂縮放尺寸:
//由於是測試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)添加了一個相框效果,若圖片加載失敗,就會顯示一個壓縮後大小相等的相框圖片:
<?xml version="1.0" encoding="utf-8"?> <ImageView xmlns:android="https://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、
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 之間的單位轉換。
Android UI 自定義控件入門——打造自己的 ImageButton
概述 我們在使用一些 App 時,應該很少看到完全不加修飾的「裸控件」吧?除非是系統內建軟體,為了風格統一而做出權衡。這裡並不是要批評 Android 原生控件不好看——
Android Service 全面整理:分類、生命週期與使用要點
Service 是 Android 四大元件之一,也是面試與實務中的高頻考點。本文把它系統性梳理一遍。 一、Service 的分類 依執行位置:分為 Local Ser
Android drawable 資料夾怎麼選?一次搞懂 mdpi、hdpi 與圖片縮放的關係
寫一個小遊戲,程式碼檢查了三遍都沒發現問題,可主界面上有幾張圖片就是莫名其妙地比設計稿大了一號。最後的解法荒唐得讓人哭笑不得——把圖片從 drawable-mdpi 換到
IPC 學習筆記:用 AIDL 實作跨進程書籍管理 Demo
最近在學習 IPC(行程間通訊),這篇把 AIDL 的使用方式完整記錄下來,並附上一個可運行的 Demo:服務端每分鐘自動新增一本書,客戶端透過跨進程呼叫取得書單,並且也