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内容變成真正的登入邏輯或注冊邏輯。