HarmonyOS实战—多按钮被点击

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内容变成真正的登录逻辑或注册逻辑。
{{o.name}}


{{m.name}}

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/app/70655.html

(0)
上一篇 2021年8月11日 18:03
下一篇 2021年8月11日 18:03

相关推荐

发表回复

登录后才能评论