compose-get路由-APT实现compose路由管理

2023-03-25  本文已影响0人  进击的小大叔

compose是android开发的未来。

官方的路由框架navigation-animation

目前官方的提供的路由框架已支持进出场动画(仅支持slide类型transition),奈何其声明与配置步骤较多,出于敏捷开发的考虑,故想开发一套类似于Arouter的路由框架。

具体实现如下

image.png

一、get-processor 注解处理器

、、、对apt不熟悉的请自行脑补

该处理器是针对使用了PageRoute 注解标注的Compolseable函数进行页面标记,将其作为 Page(页面)添加到navigation中

具体PageRoute 代码如下:

@Target(
   AnnotationTarget.FUNCTION,//对函数生效
)
@Retention(AnnotationRetention.RUNTIME)//不删除编译后保留
annotation class PageRoute(
   val route: String,// 该page的路由地址(用过arouter的应该都很熟)
   val enter: Animation = Animation.LEFT_IN, // 进场动画
   val exit: Animation = Animation.LEFT_OUT, // 出场动画
   val popEnter: Animation = Animation.RIGHT_IN,// 推出
   val popExit: Animation = Animation.RIGHT_OUT// 推入
) {
   enum class Animation {
       LEFT_IN,
       LEFT_OUT,
       RIGHT_IN,
       RIGHT_OUT,

       UP_IN,
       UP_OUT,
       DOWN_IN,
       DOWN_OUT,
   }
}

二、 使用

1. 添加注解

@Composable
@PageRoute(route = "Text")
fun MainPage() {
    Text("Main页面")
}

2.编译

rebuild 项目即可生成路由集合类扩展函数


image.png

生成扩展函数如下:

@OptIn(ExperimentalAnimationApi::class)
public fun NavGraphBuilder.appComposePages(): Unit {
  definedPage(
      route="Main",
      enter=PageRoute.Animation.LEFT_IN,
      exit=PageRoute.Animation.LEFT_OUT,
      popEnter=PageRoute.Animation.RIGHT_IN,
      popExit=PageRoute.Animation.RIGHT_OUT) {
    MainPage()
  }
}

上诉代码中扩展函数appComposePages 中的前缀即 模块名称,通过对一模块的build.gradle声明,在模块build.gradle顶级添加

kapt {
   arguments {
       arg("moduleName", project.getName())
       includeCompileClasspath = true
       generateStubs = true
   }
}

3.配置多个模块到主app

1).activity

class MainActivity : ComponentActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       WindowCompat.setDecorFitsSystemWindows(window, false)
       setContent {
           ComposeGetTheme(darkTheme = false) {
               // A surface container using the 'background' color from the theme
               App()
           }
       }
   }
}

2).App

@OptIn(ExperimentalAnimationApi::class)
@Composable
fun App() {
   GetApp(
       startDestination = "Main" //目标首页 一般为Splash
   ) {
       //添加对应模块的扩展函数
       appComposePages() // 主工程
       // module_aComposePages() 
       // module_bComposePages() 
       // module_cComposePages() 
   }
}

4.使用路由地址跳转

navigator.navigate("xxxx") ///xxxx即在PageRoute注解上的route 地址

详细参考Demo

代码已上传至mavenCentral 可直接依赖使用

各个模块build.gradle 添加

dependencies {
    .......
    implementation "io.github.sunshaobei:satis-compose-get:1.0.0"
    implementation "io.github.sunshaobei:satis-compose-get-annotation:1.0.0"
    kapt "io.github.sunshaobei:satis-compose-get-processor:1.0.0"
}
上一篇 下一篇

猜你喜欢

热点阅读