最近研究了一下,使用Compose如何去做类似ios的全屏侧滑返回效果,下面展示成果:
总共需要几个功能进行搭配使用:
1.Accompaint的Pager模块
2.通过反射使当前窗口透明以及不透明
思路分析:
pager类似于android原生的viewpager,通过初始化两个page,默认定位到Index=1的page,index=0的page将其设置为带透明背景的page,在滑动到page=0的时候,将窗口设置为透明,则实现了滑动返回效果(滑动过程中,可以看到下方页面)
至于为何使用反射来实现动态的透明窗口,而不是使用在style中设置透明背景,很多博客都有所解释,有的是说会对动画效果产生影响,有的说会导致下层activity生命周期混乱,以及加大内存开销等等,博主并没有对这些东西进行求证,有兴趣的可以自行求证,那也在这里贴一下style实现透明窗口的方式(本文并未采用这种方式):
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowIsTranslucent">true</item>
下方贴代码讲述最终实现:
首先是反射将窗口设置透明的代码:
object SlideBackUtil {
//当前是否是透明
var isTrans = false
/**
* 反射将窗口转为透明
*/
fun convertToTranslucent(activity: Activity) {
if (activity.isTaskRoot|| isTrans) return
try {
getTranslucentConversionListenerClass()?.let { listenerClass ->
val listener = getTranslucentConversionListener(listenerClass)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val activityOption =
Activity::class.java.getDeclaredMethod("getActivityOptions")
activityOption.isAccessible = true
val option = activityOption.invoke(activity)
val method = Activity::class.java.getDeclaredMethod(
"convertToTranslucent",
listenerClass,
ActivityOptions::class.java
)
method.isAccessible = true
method.invoke(activity, listener, option)
} else {
val method = Activity::class.java.getDeclaredMethod("convertToTranslucent")
method.isAccessible = true
method.invoke(activity)
}
}
//去除窗口背景
activity.window.setBackgroundDrawable(null)
isTrans=true
} catch (e: Exception) {
Log.e("tagaaa", "${e.message}")
}
}
private fun getTranslucentConversionListenerClass(): Class<*>? {
Activity::class.java.declaredClasses.forEach {
if (it.simpleName.equals("TranslucentConversionListener")) {
return it
}
}
return null
}
/**
* 获取Window透明转换监听器,在回调时通过[.setTranslucentCompleted]标记转换已完成
*/
private fun getTranslucentConversionListener(translucentConversionListenerClass: Class<*>): Any {
return Proxy.newProxyInstance(
translucentConversionListenerClass.classLoader,
arrayOf(translucentConversionListenerClass)
) { proxy, method, args ->
// setTranslucen-tCompleted(true)
// null
}
}
/**
* 反射将窗口转为不透明
*/
fun convertFromTranslucent(activity: Activity) {
if (activity.isTaskRoot|| !isTrans) return
try {
val method = Activity::class.java.getDeclaredMethod("convertFromTranslucent")
method.isAccessible = true
method.invoke(activity)
isTrans=false
} catch (e: Exception) {
Log.e("tagaaa", e.message + "")
}
}
}
然后是最终Compose函数:
@OptIn(ExperimentalPagerApi::class)
@Composable
fun SlideBackComposeTest(
activity: Activity,
content: @Composable () -> Unit,
) {
val pagerState = rememberPagerState(1)
LaunchedEffect(key1 = pagerState.currentPage, pagerState.currentPageOffset, block = {
Log.e("tagaaa","${pagerState.currentPage} ${pagerState.targetPage} ${pagerState.currentPageOffset}")
if (pagerState.currentPage == 0 && pagerState.currentPageOffset == 0f) {
activity.finish()
SlideBackUtil.isTrans = false
}
if(pagerState.currentPage==1 && pagerState.currentPageOffset!=0f){
SlideBackUtil.convertToTranslucent(activity)
}
if(pagerState.currentPage!=0&&pagerState.currentPageOffset==0f){
SlideBackUtil.convertFromTranslucent(activity)
}
})
HorizontalPager(state = pagerState, count = 2) { page ->
when (page) {
0 -> {
Box(
Modifier
.fillMaxSize()
.background(color = color_4D000000)
)
}
1 -> {
Box(modifier = Modifier.fillMaxSize()) {
content()
}
}
}
}
}
以上为所有代码,即可实现侧滑返回,方便又强大
最后:如果不想使用pager,则需要自行监听以及计算滑动参数,做相应处理,相对来说会比较麻烦,但是胜在可定制性较强,最后补一下我使用swipeable实现的另一种侧滑返回,缺点是当子布局存在可滑动组件(lazyrow等)时,会存在滑动冲突导致swipeable失效,自行取舍,如果想定制更多,或许你会想到去使用nestedscroll,dragable,scrollable,pointer等,这些博主都去尝试过,最终选用了使用pager实现,希望能给希望自定义的,提供一些思路
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun SlideBackComposeTest(
modifier: Modifier = Modifier,
activity: Activity,
content: @Composable () -> Unit,
) {
var contentWidth by remember {
mutableStateOf(0)
}
val swipeState = rememberSwipeableState(initialValue = 0)
val anchors = remember(contentWidth) {
mapOf(0f to 0, contentWidth.toFloat() to 1)
}
LaunchedEffect(key1 = swipeState.offset.value, block = {
val offset = swipeState.offset.value
if (offset == 0f) {
//背景设置不透明
SlideBackUtil.convertFromTranslucent(activity)
} else if (offset > 0f && offset < contentWidth) {
SlideBackUtil.convertToTranslucent(activity)
} else if (offset.roundToInt() >= contentWidth) {
activity.finish()
}
})
Surface(
modifier = modifier
.fillMaxSize()
.onGloballyPositioned {
contentWidth = it.size.width
}, color = color_4D000000
) {
if (contentWidth > 0) {
Box(
modifier = Modifier
.fillMaxSize()
.swipeable(
state = swipeState, anchors = anchors, thresholds = { _, _ ->
FractionalThreshold(0.5f)
},
orientation = Orientation.Horizontal
)
.offset {
IntOffset(
swipeState.offset.value
.roundToInt()
.coerceIn(0, contentWidth), 0
)
}
) {
content()
}
}
}
}
最后的最后,将activity的finish动画设置为空,即可大功告成
override fun finish() {
super.finish()
overridePendingTransition(0, 0)
}