
回复
@[toc]
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">
<Button
ohos:id="$+id:but1"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="点我"
ohos:text_size="200"
ohos:background_element="red">
</Button>
</DirectionalLayout>
MainAbilitySlice
package com.example.listenerapplication.slice;
import com.example.listenerapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
public class MainAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
//1.找到按钮
//完整写法:this.findComponentById(ResourceTable.Id_but1);
//this:本类的对象,指:MainAbilitySlice(子界面对象)
// 在子界面当中,通过 id 找到对应的组件
// 用this去调用方法,this可以省略不写
//findComponentById(ResourceTable.Id_but1);
//返回一个组件对象(所以组件的父类对象)
//那么我们在实际写代码的时候,需要向下转型:强转
Component but1 = (Button) findComponentById(ResourceTable.Id_but1);
//2.给按钮绑定单击事件,当点击后,就会执行 MyListener 中的方法,点一次执行一次
// 而方法就是下面点击的内容
but1.setClickedListener(new MyListener());
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}
class MyListener implements Component.ClickedListener{
@Override
public void onClick(Component component) {
//Component:所有组件的父类
//component参数: 被点击的组件对象,在这里就表示按你的对象
//component.setText(); setText是子类特有的方法,需要向下转型:强转
Button but = (Button) component;
but.setText("被点了");
}
}
id
找到组件。ClickedListener
接口并重写onClick
方法。onClick
方法体。