1. 创建第二个 AbilitySlice 类:
// SecondSlice.java
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
public class SecondSlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_second_slice);
Text text = (Text) findComponentById(ResourceTable.Id_second_text);
text.setTextColor(new Color(Color.getIntColor("#0000FF")));
text.setText("Welcome to the Second Page!");
}
}
2. 创建第二个布局文件:
在 resources/base/layout 目录下创建 XML 布局文件 second_slice.xml:
<!-- second_slice.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:orientation="vertical">
<Text
ohos:id="$+id/second_text"
ohos:width="match_content"
ohos:height="match_content"
ohos:text="Welcome to the Second Page!"/>
</DirectionalLayout>
3. 在 MainSlice 中添加切换到第二个页面的逻辑:
在 MainSlice.java 中添加按钮,点击按钮切换到第二个页面:
// MainSlice.java
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
public class MainSlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_main_slice);
Text text = (Text) findComponentById(ResourceTable.Id_hello_text);
text.setTextColor(new Color(Color.getIntColor("#FF0000")));
text.setText("Hello, HarmonyOS!");
// 添加按钮
Button button = (Button) findComponentById(ResourceTable.Id_switch_button);
button.setClickedListener(listener -> present(new Intent(this, SecondSlice.class)));
}
}
4. 在 MainSlice 的布局文件中添加按钮:
在 main_slice.xml 中添加按钮:
<!-- main_slice.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:orientation="vertical">
<Text
ohos:id="$+id/hello_text"
ohos:width="match_content"
ohos:height="match_content"
ohos:text="Hello, HarmonyOS!"/>
<!-- 添加按钮 -->
<Button
ohos:id="$+id/switch_button"
ohos:width="match_content"
ohos:height="wrap_content"
ohos:text="Switch to Second Page"/>
</DirectionalLayout>
5. 运行应用:
使用HarmonyOS Studio编译和运行你的应用。点击 "Switch to Second Page" 按钮,你将切换到第二个页面,显示 "Welcome to the Second Page!"。
这是一个简单的页面切换示例,你可以根据实际需求和设计,扩展和改进你的应用。在鸿蒙OS文档中可以找到更多详细的开发指南和示例代码。
转载请注明出处:http://www.zyzy.cn/article/detail/1403/鸿蒙OS