天天看點

HarmonyOS開發06:案例——多按鈕被點選

首先修改ability_main.xml檔案

添加:

<Text
    ohos:id="$+id:text1"
    ohos:height="match_content"
    ohos:width="match_content"
    ohos:text="Text"
    ohos:text_size="100"/>

<Button
    ohos:id="$+id:login"
    ohos:height="match_content"
    ohos:width="match_content"
    ohos:text="登陸"
    ohos:text_size="100"
    ohos:background_element="#FF5353B7"/>
    
<Button
    ohos:id="$+id:register"
    ohos:height="match_content"
    ohos:width="match_content"
    ohos:text="注冊"
    ohos:text_size="100"
    ohos:background_element="#FFD47A7A"/>
           

MainAbilitySlice.java整體代碼:

package com.example.listenerapplication5.slice;

import com.example.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) {
        if (component == login){
            text1.setText("點選了登陸按鈕");
        }else if (component == register){
            text1.setText("點選了注冊按鈕");
        }
    }
}