需求
做手表开发时,想要在页面内监听滑动要切换一些状态,结果发现每次滑动都自动返回或退出程序,onTouch监听不到事件。
一、禁止手表滑动返回
themes.xml:自定义主题
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="@android:style/Theme.DeviceDefault">
<item name="android:windowSwipeToDismiss">false</item>
</style>
</resources>
AndroidManifest.xml:为需要禁止滑动返沪返回的activity设置主题
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
二、MainActivity.java:监听滑动事件分发
/**
* 一般有重写dispatchTouchEvent就不再需要自定义主题
*/
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Log.e(TAG, "onTouch: 按下");
} else if (event.getAction() == MotionEvent.ACTION_UP) {
Log.e(TAG, "onTouch: 抬起");
}
return false;
}
参考:
Android中的dispatchTouchEvent()、onInterceptTouchEvent()和onTouchEvent()