中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
1.创建一个SecondAbilitySlice.java文件
public class SecondAbilitySlice extends AbilitySlice { @Override public void onStart(Intent intent) { super.onStart(intent); //super.setUIContent(ResourceTable.Layout_ability_second); //创建一个布局对象 DirectionalLayout directionalLayout = new DirectionalLayout(this); //创建一个文本对象 Text t = new Text(this); //设置文本内容 t.setText("Harmony OS"); //设置文字大小 t.setTextSize(55); //设置文字颜色 t.setTextColor(Color.BLUE); //把文本对象添加得到布局当中 directionalLayout.addComponent(t); //把布局添加到界面中 super.setUIContent(directionalLayout); } @Override public void onActive() { super.onActive(); } @Override public void onForeground(Intent intent) { super.onForeground(intent); } }
2.ability_main.xml
<DirectionalLayout xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:height="match_parent" ohos:width="match_parent" ohos:alignment="center" ohos:background_element="black" ohos:orientation="vertical"> <Text ohos:id="$+id:text_helloworld" ohos:height="match_content" ohos:width="match_content" ohos:background_element="blue" ohos:layout_alignment="horizontal_center" ohos:text="请点击下方按钮" ohos:text_size="40vp" /> <Button ohos:id="$+id:but" ohos:height="match_content" ohos:width="match_content" ohos:text="按钮" ohos:text_size="40vp" ohos:text_color="green" ohos:margin="40vp" /> </DirectionalLayout>
3.MainAbilitySlic
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener { Button but; @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_main); //拿取按钮button but = (Button)findComponentById(ResourceTable.Id_but); //2.给按钮添加一个点击事件 //理解方式 //给button添加了一个点击事件 //当我们再点击鼠标的按键的时候会执行public void onClick(Component component) 这个方法 but.setClickedListener(this); } @Override public void onActive() { super.onActive(); } @Override public void onForeground(Intent intent) { super.onForeground(intent); } @Override public void onClick(Component component) { //点击按钮之后执行的代码 //跳转到第二个页面中 if (component == but)//只有点击了button的时候才跳转 { //跳转到那个界面中(在Harmony OS中我们可以用意图) Intent t = new Intent(); //包含了要跳转的页面信息 Operation operation = new Intent.OperationBuilder() .withDeviceId("")//要跳转到哪个设备上如果传递一个没有内容的字符串表示跳转本机 .withBundleName("com.example.helloharmonyos")//我要跳转到哪个应用上 .withAbilityName("com.example.helloharmonyos.SecondAbility")//要跳转的页面 .build();//表示将上面的三个信息进行打包 //打包完成后设置一个Operation的对象设置到意图当中 t.setOperation(operation); //跳转页面 startAbility(t); } } }
4.config.json
], "orientation": "unspecified", "visible": true, "name": "com.example.helloharmonyos.MainAbility", "icon": "$media:icon", "description": "$string:mainability_description", "label": "$string:entry_MainAbility", "type": "page", "launchType": "standard" }, { "orientation": "unspecified", "name": "com.example.helloharmonyos.SecondAbility", "icon": "$media:icon", "description": "$string:secondability_description", "label": "$string:entry_SecondAbility", "type": "page", "launchType": "standard" } ] } }
5.效果图
微信扫码分享