同页面之间的Slice跳转并返回数据
下面代码有疑惑的可以参考以下
需要实现的功能
从登录成功页面跳转到另一个页面(从MainAbilitySlice跳转到ThirdSlice),并从ThirdSlice携带数据返回
- MainAbilitySlice
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
IntentData = (Text) findComponentById(ResourceTable.Id_show_intent_data);
//intent.getStringParam() 获取intent传递的参数
IntentData.setText("用户名:" + intent.getStringParam("username") + "\t密码:" + intent.getStringParam("password"));
toThird = (Button) findComponentById(ResourceTable.Id_toThird);
toThird.setClickedListener(this::toThird);
}
private void toThird(Component component) {
String msg = "我是,我是,我是凉都田鼠!";
Intent intent = new Intent();
intent.setParam("msg", msg);
presentForResult(new ThirdSlice(), intent,RESULT_CODE);
}
@Override
protected void onResult(int requestCode, Intent resultIntent) {
super.onResult(requestCode, resultIntent);
if (requestCode == RESULT_CODE) {
String msg = resultIntent.getStringParam("msg");
IntentData.setText(msg);
}
}
- ability_main
<?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:alignment="center"
ohos:orientation="vertical">
<Text
ohos:text_color="#000000"
ohos:text="登录成功"
ohos:text_size="100"
ohos:width="match_content"
ohos:height="match_content"/>
<Text
ohos:id="$+id:show_intent_data"
ohos:width="match_content"
ohos:height="match_content"
ohos:text_size="50"
ohos:text_color="#000000"/>
<Button
ohos:id="$+id:toThird"
ohos:text_color="#ffffff"
ohos:text_size="50"
ohos:top_margin="50"
ohos:background_element="$graphic:login_background"
ohos:width="match_content"
ohos:text="点击跳转"
ohos:height="match_content"/>
</DirectionalLayout>
- ThirdSlice
protected void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_third_slice_layout);
thirdText = (Text) findComponentById(ResourceTable.Id_thirdText);
thirdBack = (Button) findComponentById(ResourceTable.Id_thirdBack);
String msg = intent.getStringParam("msg");
thirdText.setText(msg);
thirdBack.setClickedListener(this::result);
}
public void result(Component component) {
Intent intent = new Intent();
intent.setParam("msg", "我是第三个页面传递的数据");
setResult(intent);
terminate();
}
- third_slice_layout
<?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:thirdText"
ohos:width="match_content"
ohos:height="match_content"
ohos:text_size="50"
ohos:text_color="#000000"/>
<Button
ohos:id="$+id:thirdBack"
ohos:width="match_content"
ohos:height="match_content"
ohos:text="BACK"
ohos:text_color="#ffffff"
ohos:background_element="$graphic:login_background"
ohos:text_size="50"
ohos:padding="20"/>
</DirectionalLayout>