多按钮的点击事件其实与只有一个是类似的,只不过要在调用 onClick()时进行判断,判断获取到的component是谁即可。
package com.example.yeman.slice;import com.example.yeman.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;@Overridepublic 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);login.setClickedListener(this);register.setClickedListener(this);}@Overridepublic void onActive() {super.onActive();}@Overridepublic void onForeground(Intent intent) {super.onForeground(intent);}@Overridepublic void onClick(Component component) {//先做一个判断//判断当前点击的是登录按钮还是注册按钮//component表示当前点击的组件if(component == login){//表示现在点击的是登录按钮text1.setText("点击了登录按钮");}else if(component == register){//表示现在点击的是注册按钮text1.setText("点击了注册按钮");}}
}