样式
代码
ability_main.xml
<?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:background_element="#D9D9D9"
ohos:orientation="vertical">
<Image
ohos:height="match_content"
ohos:width="match_content"
ohos:image_src="$media:photo"
ohos:layout_alignment="horizontal_center"
ohos:top_margin="100vp"
/>
<Text
ohos:id="$+id:message"
ohos:height="50vp"
ohos:width="320vp"
ohos:layout_alignment="horizontal_center"
ohos:text="当我女朋友好吗?"
ohos:text_alignment="center"
ohos:text_size="35fp"
ohos:top_margin="30vp"
/>
<Button
ohos:id="$+id:submit"
ohos:height="50vp"
ohos:width="320vp"
ohos:background_element="#92D050"
ohos:layout_alignment="horizontal_center"
ohos:text="好的"
ohos:text_alignment="center"
ohos:text_color="#FEFEFE"
ohos:text_size="30fp"
ohos:top_margin="20vp"
/>
<Button
ohos:id="$+id:cacel"
ohos:height="50vp"
ohos:width="320vp"
ohos:background_element="#92D050"
ohos:layout_alignment="horizontal_center"
ohos:text="不好"
ohos:text_alignment="center"
ohos:text_color="#FEFEFE"
ohos:text_size="30fp"
ohos:top_margin="20vp"
ohos:top_padding="10vp"
/>
</DirectionalLayout>
MainAbilitySlice.java
package com.example.myapplication.slice;
import com.example.myapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.multimodalinput.event.TouchEvent;
import java.util.Random;
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
Text message;
Button submit;
Button cacel;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
//1. 找到组件
message = (Text) findComponentById(ResourceTable.Id_message);
submit = (Button) findComponentById(ResourceTable.Id_submit);
cacel = (Button) findComponentById(ResourceTable.Id_cacel);
//2. 给按钮添加单击事件
submit.setClickedListener(this);
cacel.setClickedListener(this);
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
//表示点击了不好的次数
int count = 0;
//创建随机值
Random r = new Random();
@Override
public void onClick(Component component) {
//判断点击了那个按钮
if (component == submit){
message.setText("恭喜你!");
//同时在后台发送一个确认消息
//取消两个按钮的点击事件
submit.setClickable(false);
cacel.setClickable(false);
}else if (component == cacel){
count++;
if (count == 1){
//第一次点击
message.setText("手滑了把?再点一次吧");
//用代码设置文字大小,单位是像素px
message.setTextSize(60);
//把不好的按钮进行随机摆放
int x = r.nextInt(500);
int y = r.nextInt(1000);
cacel.setTranslation(x,y);
}else{
message.setText("我是你永远得不到的男人");
//取消两个按钮的点击事件
submit.setClickable(false);
cacel.setClickable(false);
}
}
}
}