HarmonyOS应用开发基础——点击事件的绑定
HarmonyOS应用开发基础
点击事件的四种写法
首先在ability_main.xml中添加一个Button和Text`
<Button
ohos:id="$+id:but1"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="点我"
ohos:text_size="200"
ohos:background_element="red"
/>
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:id="$+id:text1"
ohos:text="text"
ohos:text_size="100"
/>
第一种方法:定义实现类
首先我们需要去找到我们之前已经定义的button和Text,通过id查到
在最外层定义全局变量text1
Text text1=null;
//1.找到按钮和文本框
Button but1=(Button)findComponentById(ResourceTable.Id_but1);
text1=(Text)findComponentById(ResourceTable.Id_text1);
第二步便是绑定单击事件
//2.给按钮绑定单击事件
but1.setClickedListener(new MyListener());
在MainAbilitySlice.java文件中,自己创建一个类MyListener,实现接口 Component.ClickedListener
class MyListener implements Component.ClickedListener
{
@Override
public void onClick(Component component) {
//component:所有组件的父类
//参数:被点击的组件对象
Button but=(Button)component;
but.setText("第一种方法点击");
}
}
第二种方法:当前类作为实现类
在最外层的主类直接引用接口 implements Component.ClickedListener,实现onclick方法。
@Override
public void onClick(Component component)
{
Button btu=(Button)component;
btu.setText