需要获取按下时候的坐标和松开时候的坐标,并将两者进行比较。
①MainAbilitySlice.java文件
可以根据使用情况做修改代码中判断处的限制偏差范围。
package com.example.yeman.slice;import com.example.yeman.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Text;
import ohos.media.image.common.Position;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;public class MainAbilitySlice extends AbilitySlice implements Component.TouchEventListener{float starX;float starY;float endX;float endY;Text txt;@Overridepublic void onStart(Intent intent) {super.onStart(intent);super.setUIContent(ResourceTable.Layout_ability_main);//通过id找到布局对象(其也可以理解是一种组件)DirectionalLayout dl = (DirectionalLayout) findComponentById(ResourceTable.Id_dl);//通过id找到文本框组件txt = (Text) findComponentById(ResourceTable.Id_txt);//给整个布局添加滑动事件,当在整个布局上滑动时,就会不断调用本类中onTouchEvent方法dl.setTouchEventListener(this);}@Overridepublic void onActive() {super.onActive();}@Overridepublic void onForeground(Intent intent) {super.onForeground(intent);}@Overridepublic boolean onTouchEvent(Component component, TouchEvent touchEvent) {//component表示滑动的哪个组件,布局也是一种组件,实际上这里示例就是在整个布局上进行的。//touchEvent表示动作对象(按下,滑动,抬起)。//获取当前手指对于屏幕进行的操作(按下,滑动,抬起)int action = touchEvent.getAction(); //1表示按下,2表示抬起,3表示滑动(移动)if (action == TouchEvent.PRIMARY_POINT_DOWN){MmiPoint position = touchEvent.getPointerPosition(0);starX = position.getX();starY = position.getY();txt.setText(starX + "--" + starY);}else if (action == TouchEvent.PRIMARY_POINT_UP){MmiPoint position = touchEvent.getPointerPosition(0);endX = position.getX();endY = position.getY();txt.setText(endX + "--" + endY);//Math.abs(starY - endY) < 100是做一个Y方向的限定范围,下面类似。if (starX > endX && Math.abs(starY - endY) < 100){txt.setText("左滑了");}else if (starX < endX && Math.abs(starY - endY) < 100){txt.setText("右滑了");}else if (starY > endY && Math.abs(starX - endX) < 100){txt.setText("上滑了");}else if (starY < endY && Math.abs(starX - endX) < 100){txt.setText("下滑了");}else txt.setText("无效滑动(请直一点!)");}else if (action == TouchEvent.POINT_MOVE){txt.setText("滑动中...");}return true;}
}
②ability _main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayoutohos:id="$+id:dl"xmlns:ohos="http://schemas.huawei.com/res/ohos"ohos:height="match_parent"ohos:width="match_parent"ohos:alignment="center"ohos:orientation="vertical"><Textohos:id="$+id:txt"ohos:height="match_content"ohos:width="match_content"ohos:text="这里是文本框"ohos:text_size="100"/></DirectionalLayout>