(3.5)HarmonyOS鸿蒙上下左右方向滑动
生活随笔
收集整理的這篇文章主要介紹了
(3.5)HarmonyOS鸿蒙上下左右方向滑动
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
需要獲取按下時(shí)候的坐標(biāo)和松開時(shí)候的坐標(biāo),并將兩者進(jìn)行比較。
①M(fèi)ainAbilitySlice.java文件
可以根據(jù)使用情況做修改代碼中判斷處的限制偏差范圍。
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);//給整個(gè)布局添加滑動(dòng)事件,當(dāng)在整個(gè)布局上滑動(dòng)時(shí),就會(huì)不斷調(diào)用本類中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表示滑動(dòng)的哪個(gè)組件,布局也是一種組件,實(shí)際上這里示例就是在整個(gè)布局上進(jìn)行的。//touchEvent表示動(dòng)作對象(按下,滑動(dòng),抬起)。//獲取當(dāng)前手指對于屏幕進(jìn)行的操作(按下,滑動(dòng),抬起)int action = touchEvent.getAction(); //1表示按下,2表示抬起,3表示滑動(dòng)(移動(dòng))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是做一個(gè)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("無效滑動(dòng)(請直一點(diǎn)!)");}else if (action == TouchEvent.POINT_MOVE){txt.setText("滑動(dòng)中...");}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>總結(jié)
以上是生活随笔為你收集整理的(3.5)HarmonyOS鸿蒙上下左右方向滑动的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 云之家如何找到自己的公司
- 下一篇: (3.5)HarmonyOS鸿蒙多按钮点