Skip to content

2、UI跳转

mqzhangw edited this page Mar 26, 2018 · 1 revision

UI跳转进过一次大的改版,目前采用中央路由+注解生成的方案实现

组件添加必要的依赖

在组件的build.gradle中添加依赖

annotationProcessor 'com.luojilab.ddcomponent:router-anno-compiler:1.0.0'

同时添加

defaultConfig {
    javaCompileOptions {
        annotationProcessorOptions {
             arguments = [host: "share"]
        }
    }
}

此处的"share"是跳转URI中的host,每个组件需要设置不同的host。

注册组件到UIRouter中

在组件的声明周期类ApplicationLike中,添加注册和反注册代码

public class ShareApplike implements IApplicationLike {
    UIRouter uiRouter = UIRouter.getInstance();
    @Override
    public void onCreate() {
        uiRouter.registerUI("share");
    }
    @Override
    public void onStop() {
        uiRouter.unregisterUI("share");
    }
}

目标页面添加注解

首先在跳转的目的Activity上添加RouteNode注解

@RouteNode(path = "/shareBook", desc = "分享书籍页面")
public class ShareActivity extends AppCompatActivity {

如果需要传入参数,在具体的参数定义上增加Autowired注解:

@Autowired
String bookName;
@Autowired
Author author;

注意此处的参数需要设置为非private,否则编译会直接报错

自动装载

如果想使用自动装载功能,需要在Activity的onCreate中调用方法

AutowiredService.Factory.getInstance().create().autowire(this);

建议改方法在基类Activity中调用

build项目

项目执行build,会生成apt文件,具体可在build目录下面查看 同时还会在根目录生成UIRouterTable文件夹,里面会列出每个组件向外提供的路由表

auto generated, do not change !!!! 

HOST : share

分享杂志页面
/shareMagazine
author:com.luojilab.componentservice.share.bean.Author
bookName:String

分享书籍页面
/shareBook
author:com.luojilab.componentservice.share.bean.Author
bookName:String

跳转

在发起跳转页面,有三种方式可以跳转到目的页面

Bundle方式

    // UI transfer with Bundle
    private void goToShareActivityWithBundle() {
        Author author = new Author();
        author.setName("Margaret Mitchell");
        author.setCounty("USA");
        Bundle bundle = new Bundle();
        bundle.putString("bookName", "Gone with the Wind");
        bundle.putString("author", JsonService.Factory.getInstance()
                .create().toJsonString(author));
        UIRouter.getInstance().openUri(getActivity(), "DDComp://share/shareBook", bundle);
    }

URI方式

    // UI transfer with URI
    private void goToShareActivityWithUri() {
        Author author = new Author();
        author.setName("Barack Obama");
        author.setCounty("New York");
        final String URI_LEGAL = "DDComp://share/shareMagazine?bookName=NYTIME&author=";
        legal and illegal data delivering*/
        UIRouter.getInstance().openUri(getActivity(),
                URI_LEGAL
                        + JsonService.Factory.getInstance().create().toJsonString(author), null);
    }

startActivityForResult

    //startActivityForResult
    private void goToShareActivityForResult() {
        Author author = new Author();
        author.setName("Margaret Mitchell");
        author.setCounty("USA");
        UIRouter.getInstance().openUri(getActivity(),
                "DDComp://share/shareBook?bookName=Gone with the Wind&author="
                        + JsonService.Factory.getInstance().create().toJsonString(author), null, 7777);
    }