回复
HarmonyOS实战—多按钮被点击 原创
兮动人
发布于 2021-7-30 11:11
浏览
1收藏
@[toc]
1. 多按钮被点击
- 新建项目:ListenerApplication5
- 实现代码:
ability_main
<?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:text1"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="Text"
ohos:text_size="100">
</Text>
<Button
ohos:id="$+id:login"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="登录"
ohos:text_size="100"
ohos:background_element="cyan">
</Button>
<Button
ohos:id="$+id:register"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="注册"
ohos:text_size="100"
ohos:background_element="red"
>
</Button>
</DirectionalLayout>
MainAbilitySlice
package com.xdr630.listenerapplication5.slice;
import com.xdr630.listenerapplication5.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.Text;
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener{
Text text1;
Button login;
Button register;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
//1.找到文本、按钮组件
text1 = (Text) findComponentById(ResourceTable.Id_text1);
login = (Button) findComponentById(ResourceTable.Id_login);
register = (Button) findComponentById(ResourceTable.Id_register);
//2.给按钮绑定事件
//要对哪个组件做什么操作?
//要对登录按钮,注册按钮做点击操作
login.setClickedListener(this);
register.setClickedListener(this);
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
@Override
public void onClick(Component component) {
//先做一个判断
//判断当前点击的按钮时登录按钮还是注册按钮
//component:表示当前点击的组件
if (component == login){
//表示点击的是登录按钮
text1.setText("点击了登录按钮");
}else if (component == register){
//表示点击的是注册按钮
text1.setText("点击了注册按钮");
}
}
}
- 运行:
- 点击登录按钮:
- 点击注册按钮:
2. 小节
- 以后要写到登录逻辑或注册逻辑,整体的架构就是跟这个案例类似的,唯一的不同就是把setText内容变成真正的登录逻辑或注册逻辑。
©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
分类
赞
2
收藏 1
回复
相关推荐