06. 案例1 多按钮被点击

本文档展示了在Ohos平台上如何使用DirectionalLayout创建界面,并通过XML布局文件设置Text和Button组件。同时,讲解了在MainAbilitySlice.java中如何找到组件并为其绑定点击事件,实现点击按钮后更新文本内容的功能。
摘要由CSDN通过智能技术生成

显示效果

代码示例 

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: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"
        />

    <Button
        ohos:id="$+id:register"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="注册"
        ohos:text_size="100"
        ohos:background_element="red"
        />

</DirectionalLayout>

MainAbilitySlice.java

package com.example.myapplication.slice;

import com.example.myapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.OnClickListener;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Text;
import ohos.javax.xml.stream.events.EndElement;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

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) {
        //现在需要判断当前的按钮是登录按钮还是注册按钮
        if(component == login)
        {   //表示点击了登录按钮
            text1.setText("点击了登录按钮");
        }else if (component == register){
            text1.setText("点击了注册按钮");
        }


    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值