Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

第24章 Android OnLongClickListener 長按事件:把圖片設成手機桌布

編輯:Android 技術基礎

OnLongClick 指的是「長按約兩秒以上才觸發」的事件。它和 OnClickListener 的原理幾乎一樣,差別只在觸發的時間門檻。本章用一個圖片瀏覽器當例子:點擊按鈕換圖,長按圖片則把當前這張設成手機桌布。

一、回呼方法與回傳值

public boolean onLongClick(View v)

參數 v 是事件來源元件,只有長時間按住它才會進入這個方法。回傳值的意思是:

  • true:這個事件我已經完整處理,不希望其他回呼再接手。
  • false:我沒有處理完,希望其他方法繼續處理。

二、準備圖片與版面

把 a.jpg、b.jpg、c.jpg、d.jpg、e.jpg 與 prov.png、next.png 複製到 res/drawable-hdpi。

開啟 res/layout/activity_main.xml,從 Image&Media 拖出 1 個 ImageView 與 2 個 ImageButton。

接著調整幾個屬性:ImageView 的 id 改為 picture、「上一幅」的 id 改為 prov、「下一幅」改為 next,並為兩個按鈕加上 android:padding="0dp" 去掉周邊的灰色邊框,讓圖示能貼齊設計稿。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="18dp"
        android:src="@drawable/a" />

    <ImageButton
        android:id="@+id/prov"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/picture"
        android:layout_marginLeft="38dp"
        android:layout_marginTop="16dp"
        android:padding="0dp"
        android:src="@drawable/prov" />

    <ImageButton
        android:id="@+id/next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/prov"
        android:layout_marginRight="24dp"
        android:padding="0dp"
        android:src="@drawable/next" />
</RelativeLayout>

三、程式實作

開啟 src/com.genwoxue.onlongclick/MainActivity.java:

package com.example.onlongclick;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private ImageView ivwPicture = null;
    private ImageButton ibtnProv = null;
    private ImageButton ibtnNext = null;

    private Integer[] iImages = {
        R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e
    };

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

        ivwPicture = (ImageView) findViewById(R.id.picture);
        ibtnProv   = (ImageButton) findViewById(R.id.prov);
        ibtnNext   = (ImageButton) findViewById(R.id.next);

        ibtnProv.setOnClickListener(new View.OnClickListener() {
            private int i = 0;
            @Override
            public void onClick(View v) {
                i = (i - 1 + iImages.length) % iImages.length;
                ivwPicture.setImageResource(iImages[i]);
            }
        });

        ibtnNext.setOnClickListener(new View.OnClickListener() {
            private int i = 0;
            @Override
            public void onClick(View v) {
                i = (i + 1) % iImages.length;
                ivwPicture.setImageResource(iImages[i]);
            }
        });

        ivwPicture.setOnLongClickListener(new PicOnLongClick());
    }

    /** 長按圖片:把當前顯示的圖片設為桌布 */
    private class PicOnLongClick implements View.OnLongClickListener {
        @Override
        public boolean onLongClick(View view) {
            try {
                clearWallpaper();                       // 先清掉目前桌布

                ImageView iv = (ImageView) view;
                iv.setDrawingCacheEnabled(true);        // 啟用繪圖快取
                Bitmap bmp = Bitmap.createBitmap(iv.getDrawingCache());
                setWallpaper(bmp);                      // 設為桌布
                iv.setDrawingCacheEnabled(false);       // 用完立刻關掉,避免浪費記憶體

                Toast.makeText(MainActivity.this, "背景設定成功!", Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(MainActivity.this, "背景設定失敗!", Toast.LENGTH_LONG).show();
            }
            return true;
        }
    }
}

範例把索引改成用取餘數 % 遞增遞減,比原本寫一串 if 判斷更簡短,也不會在頭尾處出錯。

為什麼要開 DrawingCache? 圖片顯示在畫面上時,你手上只有一個 ImageView 物件,並沒有 Bitmap 可以直接交給 setWallpaper()。DrawingCache 會把元件目前渲染的結果存成一張圖,讓你能把它取出來 reuse。

四、别忘了權限

設定桌布屬於會改動系統狀態的操作,必須在 AndroidManifest.xml 宣告權限,否則執行時會直接拋出 SecurityException:

<uses-permission android:name="android.permission.SET_WALLPAPER" />

完整清單檔:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.onlongclick"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.SET_WALLPAPER" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.example.onlongclick.MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

五、實務提醒

新版 Android 對桌布 API 有了更完整的做法( wallpaperManager 家族),而 DrawingCache 這種取圖方式在硬體加速環境下並不總是可靠,回傳 null 的情況並不少見——所以範例一定要包在 try-catch 裡。若要在正式專案實作,建議直接從 drawable 資源讀取原始 Bitmap,繞過 DrawingCache 這層。

六、執行結果

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