- 编写第一个页面(使用xml)
- 编写第二个页面(使用Java)
- 添加单击事件
编写页面有两个方式,一是通过xml文件,二是通过Java代码。
编写第一个页面(使用xml)
直接改写默认的MainAbility,如下
编写第二个页面(使用Java)
先新建一个页面,如下
开发工具会自动生成一些文件,如下 在此我们不用xml编写,因此可以将3删掉,在1中编写代码:public class SecondAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
// super.setUIContent(ResourceTable.Layout_ability_second);
// 声明布局
DirectionalLayout myLayout = new DirectionalLayout(this);
// 设置布局背景为白色
ShapeElement background = new ShapeElement();
background.setRgbColor(new RgbColor(255, 255, 255));
myLayout.setBackground(background);
// 创建一个文本
Text text = new Text(this);
text.setText("第二个界面");
text.setWidth(DirectionalLayout.LayoutConfig.MATCH_PARENT);
text.setTextSize(100);
text.setTextColor(Color.BLACK);
// 设置文本的布局
DependentLayout.LayoutConfig textConfig = new DependentLayout.LayoutConfig(DependentLayout.LayoutConfig.MATCH_CONTENT, DependentLayout.LayoutConfig.MATCH_CONTENT);
textConfig.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT);
text.setLayoutConfig(textConfig);
//把文本对象添加到布局中
myLayout.addComponent(text);
//把布局添加到界面中
super.setUIContent(myLayout);
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}
添加单击事件
public class MainAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
Button button = (Button) findComponentById(ResourceTable.Id_button1);
// 点击按钮跳转至第二个页面
button.setClickedListener(listener -> present(new SecondAbilitySlice(), new Intent()));
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}
此时运行就可以看到效果了



