布局
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:alignment="center"
ohos:orientation="vertical">
<Text
ohos:id="$+id:text_helloworld"
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="$graphic:background_ability_main"
ohos:layout_alignment="horizontal_center"
ohos:text="第一个页面"
ohos:text_size="40vp"
/>
<Button
ohos:id="$+id:btn1"
ohos:height="match_content"
ohos:width="match_parent"
ohos:background_element="red"
ohos:text="跳转下一个页面"
ohos:text_size="40fp"/>
<Button
ohos:id="$+id:btn2"
ohos:height="match_content"
ohos:width="match_parent"
ohos:background_element="red"
ohos:text="滑动"
ohos:text_size="40fp"/>
</DirectionalLayout>
代码
package com.example.helloworld.slice;
import com.example.helloworld.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.window.dialog.ToastDialog;
import ohos.multimodalinput.event.TouchEvent;
public class MainAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
Button btn1 = findComponentById(ResourceTable.Id_btn1);
Button btn2 = findComponentById(ResourceTable.Id_btn2);
btn1.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
Intent intent = new Intent();
//withDeviceId 跳转到那个设备上,如果传递一个没有内容的字符串 标识跳转本机
//withBundleName 跳转那个应用上面
//withAbilityName 要跳转的页面
Operation build = new Intent.OperationBuilder()
.withDeviceId("")
.withBundleName("com.example.helloworld")
.withAbilityName(".SecondAbility")
.build();
intent.setOperation(build);
startAbility(intent);
}
});
btn1.setDoubleClickedListener(new Component.DoubleClickedListener() {
@Override
public void onDoubleClick(Component component) {
btn1.setText("我被双击了");
}
});
btn1.setLongClickedListener(new Component.LongClickedListener() {
@Override
public void onLongClicked(Component component) {
btn1.setText("我被长按了");
}
});
btn2.setTouchEventListener(new Component.TouchEventListener() {
@Override
public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
int action = touchEvent.getAction();
switch (action){
//按下
case TouchEvent.PRIMARY_POINT_DOWN:
btn2.setText("按下");
break;
//弹起
case TouchEvent.PRIMARY_POINT_UP:
btn2.setText("弹起");
break;
//滑动
case TouchEvent.POINT_MOVE:
btn2.setText("滑动");
break;
}
return true;
}
});
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}
这里记得修改为true
否则可能会只有按下事件