> 文档中心 > 《HarmonyOS实战 — 页面跳转案例》

《HarmonyOS实战 — 页面跳转案例》

【本文正在参与“有奖征文 | HarmonyOS征文大赛”活动】

1.界面布局

鸿蒙UI中,提供了两种编写布局的方式

  • 在XML中声明UI布局
  • 在代码中创建布局

这两种方式创建出的布局没有本质差别,但是XML方式较为方便简单,以后开发中,也都是用XML布局的方式。
但是这两种方式都需要我们熟悉。所以,所以我们将通过XML的方式布局第一张页面,然后再通过代码的方式布局
第二张页面。

1.1 XML文件方式配置界面

  1. 打开layout下面的“ability_main.xml”文件
  2. 在“ability_main.xml”文件中创建一个文本Text和一个按钮Button
<?xml version="1.0" encoding="utf-8"?><DependentLayoutxmlns:ohos="http://schemas.huawei.com/res/ohos"ohos:width="match_parent"ohos:height="match_parent"ohos:background_element="#000000"><Textohos:id="$+id:text"ohos:width="match_content"ohos:height="match_content"ohos:text="Hello World"ohos:text_color="white"ohos:text_size="32fp"ohos:center_in_parent="true"/><Buttonohos:id="$+id:button"ohos:width="match_content"ohos:height="match_content"ohos:text="Next"ohos:text_size="19fp"ohos:text_color="white"ohos:top_padding="8vp"ohos:bottom_padding="8vp"ohos:right_padding="80vp"ohos:left_padding="80vp"ohos:background_element="$graphic:background_button"ohos:below="$id:text"ohos:horizontal_center="true" /></DependentLayout>

1.2 代码方式配置界面

1. 创建Feature Ability2. 代码编写界面
public class SecondAbilitySlice extends AbilitySlice {@Overridepublic void onStart(Intent intent) {super.onStart(intent); // 声明布局DependentLayout myLayout = new DependentLayout(this); // 设置页面布局大小和背景色myLayout.setWidth(MATCH_PARENT); myLayout.setHeight(MATCH_PARENT); ShapeElement element = new ShapeElement(); element.setRgbColor(new RgbColor(255, 255, 255)); myLayout.setBackground(element); // 创建一个文本Text text = new Text(this); text.setText("Nice to meet you."); text.setTextSize(55); text.setTextColor(Color.BLACK); // 设置文本的布局DependentLayout.LayoutConfig textConfig = newDependentLayout.LayoutConfig(MATCH_CONTENT,MATCH_CONTENT); textConfig.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT); text.setLayoutConfig(textConfig); myLayout.addComponent(text); super.setUIContent(myLayout); }@Overridepublic void onActive() {super.onActive(); }@Overridepublic void onForeground(Intent intent) {super.onForeground(intent);}}

1.3 代码实现页面跳转

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {Button button;@Overridepublic void onStart(Intent intent) {super.onStart(intent);super.setUIContent(ResourceTable.Layout_ability_main);button = (Button) findComponentById(ResourceTable.Id_text_button);button.setClickedListener(this);}@Overridepublic void onActive() {super.onActive();}@Overridepublic void onForeground(Intent intent) {super.onForeground(intent);}@Overridepublic void onClick(Component component) {if(component == button){//跳转页面//创建一个意图对象。Intent i = new Intent();//创建意图的参数对象。Operation operation = new Intent.OperationBuilder().withDeviceId("")//本机.withBundleName("com.example.myapplication")//哪个应用.withAbilityName("com.example.myapplication.Second_Ability")//哪个界面.build();i.setOperation(operation);startAbility(i);}}}

【本文正在参与“有奖征文 | HarmonyOS征文大赛”活动】

医学名词百科