首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 在其他類中調用 Activity 的 dispatchTouchEvent:封裝為獨立監聽器類

     編輯:程式設計綜合問答

需求

將 `dispatchTouchEvent` 中的震動邏輯提取,供其他類/函數復用。

方案:創建實現 OnTouchListener 的獨立類

public class VibrateTouchListener implements View.OnTouchListener {
    private final Vibrator vibrator;
    private final Random random = new Random();

    public VibrateTouchListener(Context context) {
        vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            int duration = random.nextInt(500) + 4000; // 4000-4500ms
            vibrator.vibrate(duration);
        }
        return false; // 不攔截事件,繼續分發
    }
}

使用方式

// 在 Activity 中
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setOnTouchListener(new VibrateTouchListener(this));

// 或針對特定 View
button.setOnTouchListener(new VibrateTouchListener(this));

進階:全局攔截

若需**全局**攔截所有觸摸事件,可在 Application 中註冊 `ActivityLifecycleCallbacks`,為每個 Activity 的 `getWindow().getDecorView()` 設置同一 Listener 實例。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved