这交互炸了系列:仿小米音乐歌手详情页,自定义-Behavior实战

public ContentBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
//引入尺寸值
int resourceId = context.getResources().getIdentifier(“status_bar_height”, “dimen”, “android”);
int statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
topBarHeight= (int) context.getResources().getDimension(R.dimen.top_bar_height)+statusBarHeight;
contentTransY= (int) context.getResources().getDimension(R.dimen.content_trans_y);
downEndY= (int) context.getResources().getDimension(R.dimen.content_trans_down_end_y);

}

@Override
public boolean onMeasureChild(@NonNull CoordinatorLayout parent, View child,
int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec,int heightUsed) {
final int childLpHeight = child.getLayoutParams().height;
if (childLpHeight == ViewGroup.LayoutParams.MATCH_PARENT
|| childLpHeight == ViewGroup.LayoutParams.WRAP_CONTENT) {
//先获取CoordinatorLayout的测量规格信息,若不指定具体高度则使用CoordinatorLayout的高度
int availableHeight = View.MeasureSpec.getSize(parentHeightMeasureSpec);
if (availableHeight == 0) {
availableHeight = parent.getHeight();
}
//设置Content部分高度
final int height = availableHeight - topBarHeight;
final int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(height,
childLpHeight == ViewGroup.LayoutParams.MATCH_PARENT
? View.MeasureSpec.EXACTLY
: View.MeasureSpec.AT_MOST);
//执行指定高度的测量,并返回true表示使用Behavior来代理测量子View
parent.onMeasureChild(child, parentWidthMeasureSpec,
widthUsed, heightMeasureSpec, heightUsed);
return true;
}
return false;
}

@Override
public boolean onLayoutChild(@NonNull CoordinatorLayout parent, @NonNull View child, int layoutDirection) {
boolean handleLayout = super.onLayoutChild(parent, child, layoutDirection);
//绑定Content View
mLlContent=child;
return handleLayout;
}
}

实现NestedScrollingParent2接口
onStartNestedScroll()

ContentBehavior只处理Content部分里可滑动View的垂直方向的滑动。

public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child,
@NonNull View directTargetChild, @NonNull View target, int axes, int type) {
//只接受内容View的垂直滑动
return directTargetChild.getId() == R.id.ll_content
&&axes== ViewCompat.SCROLL_AXIS_VERTICAL;
}

onNestedPreScroll()

接下来就是处理滑动,上面效果分析提过:

Content部分的:

上滑范围=[topBarHeight,contentTransY]、
下滑范围=[contentTransY,downEndY]即滑动范围为[topBarHeight,downEndY];

ElemeNestedScrollLayout要控制Content部分的TransitionY值要在范围内,具体处理如下:

Content部分里可滑动View往上滑动时:

  1. 如果Content部分当前TransitionY+View滑动的dy > topBarHegiht,设置Content部分的TransitionY为Content部分当前TransitionY+View滑动的dy达到移动的效果来消费View的dy。

  2. 如果Content部分当前TransitionY+View滑动的dy = topBarHegiht,同上操作。

  3. 如果Content部分当前TransitionY+View滑动的dy < topBarHegiht,只消费部分dy(即Content部分当前TransitionY到topBarHeight差值),剩余的dy让View滑动消费。

Content部分里可滑动View往下滑动并且View已经不能往下滑动
(比如RecyclerView已经到顶部还往下滑)时:

  1. 如果Content部分当前TransitionY+View滑动的dy >= topBarHeight 并且 Content部分当前TransitionY+View滑动的dy <= downEndY,设置Content部分的TransitionY为Content部分当前TransitionY+View滑动的dy达到移动的效果来消费View的dy

  2. Content部分当前TransitionY+View滑动的dy > downEndY,只消费部分dy(即Content部分当前TransitionY到downEndY差值)并停止NestedScrollingChild2的View滚动。

public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child,
@NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) {
float transY = child.getTranslationY() - dy;

//处理上滑
if (dy > 0) {
if (transY >= topBarHeight) {
translationByConsume(child, transY, consumed, dy);
} else {
translationByConsume(child, topBarHeight, consumed, (child.getTranslationY() - topBarHeight));
}
}

if (dy < 0 && !target.canScrollVertically(-1)) {
//处理下滑
if (transY >= topBarHeight && transY <= downEndY) {
translationByConsume(child, transY, consumed, dy);
} else {
translationByConsume(child, downEndY, consumed, (downEndY-child.getTranslationY()));
stopViewScroll(target);
}
}
}

private void stopViewScroll(View target){
if (target instanceof RecyclerView) {
((RecyclerView) target).stopScroll();
}
if (target instanceof NestedScrollView) {
try {
Class<? extends NestedScrollView> clazz = ((NestedScrollView) target).getClass();
Field mScroller = clazz.getDeclaredField(“mScroller”);
mScroller.setAccessible(true);
OverScroller overScroller = (OverScroller) mScroller.get(target);
overScroller.abortAnimation();
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
}

private void translationByConsume(View view, float translationY, int[] consumed, float consumedDy) {
consumed[1] = (int) consumedDy;
view.setTranslationY(translationY);
}

onStopNestedScroll()

在下滑Content部分从初始状态转换到展开状态的过程中松手就会执行收起的动画,这逻辑在onStopNestedScroll()实现,但注意如果动画未执行完毕手指再落下滑动时,应该在onNestedScrollAccepted()取消当前执行中的动画。

private static final long ANIM_DURATION_FRACTION = 200L;
private ValueAnimator restoreAnimator;//收起内容时执行的动画

public ContentBehavior(Context context, AttributeSet attrs) {

restoreAnimator = new ValueAnimator();
restoreAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
translation(mLlContent, (float) animation.getAnimatedValue());
}
});
}

public void onNestedScrollAccepted(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child,
@NonNull View directTargetChild, @NonNull View target, int axes, int type) {
if (restoreAnimator.isStarted()) {
restoreAnimator.cancel();
}
}

public void onStopNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target, int type) {
//如果是从初始状态转换到展开状态过程触发收起动画
if (child.getTranslationY() > contentTransY) {
restore();
}
}

private void restore(){
if (restoreAnimator.isStarted()) {
restoreAnimator.cancel();
restoreAnimator.removeAllListeners();
}
restoreAnimator.setFloatValues(mLlContent.getTranslationY(), contentTransY);
restoreAnimator.setDuration(ANIM_DURATION_FRACTION);
restoreAnimator.start();
}

private void translation(View view, float translationY) {
view.setTranslationY(translationY);
}

处理惯性滑动

**场景1:**快速往上滑动Content部分的可滑动View产生惯性滑动,这和前面onNestedPreScroll()处理上滑的效果一模一样,因此可以复用逻辑。

**场景2:**从初始化状态快速下滑转为展开状态,这也和和前面onNestedPreScroll()处理上滑的效果一模一样,因此可以复用逻辑。

**场景3:**从折叠状态快速下滑转为初始化状态,这个过程如下图,看起来像是快速下滑停顿的效果。

public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child,

@NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) {
float transY = child.getTranslationY() - dy;

if (dy < 0 && !target.canScrollVertically(-1)) {
//下滑时处理Fling,折叠时下滑Recycler(或NestedScrollView) Fling滚动到contentTransY停止Fling
if (type == ViewCompat.TYPE_NON_TOUCH&&transY >= contentTransY&&flingFromCollaps) {
flingFromCollaps=false;
translationByConsume(child, contentTransY, consumed, dy);
stopViewScroll(target);
return;
}

}
}

释放资源

在ContentBehavior被移除时候,执行要停止动画、释放监听者的操作。

public void onDetachedFromLayoutParams() {
if (restoreAnimator.isStarted()) {
restoreAnimator.cancel();
restoreAnimator.removeAllUpdateListeners();
restoreAnimator.removeAllListeners();
restoreAnimator = null;
}
super.onDetachedFromLayoutParams();
}

FaceBehavior

这个Behavior主要处理Face部分的ImageView的位移、蒙层的透明度变化,这里因为篇幅原因,只讲解关键方法,具体源码见

public class FaceBehavior extends CoordinatorLayout.Behavior {
private int topBarHeight;//topBar内容高度
private float contentTransY;//滑动内容初始化TransY
private float downEndY;//下滑时终点值
private float faceTransY;//图片往上位移值

public FaceBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
//引入尺寸值
int resourceId = context.getResources().getIdentifier(“status_bar_height”, “dimen”, “android”);
int statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
topBarHeight= (int) context.getResources().getDimension(R.dimen.top_bar_height)+statusBarHeight;
contentTransY= (int) context.getResources().getDimension(R.dimen.content_trans_y);
downEndY= (int) context.getResources().getDimension(R.dimen.content_trans_down_end_y);
faceTransY= context.getResources().getDimension(R.dimen.face_trans_y);

}

public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
//依赖Content View
return dependency.getId() == R.id.ll_content;
}

public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
//计算Content的上滑百分比、下滑百分比
float upPro = (contentTransY- MathUtils.clamp(dependency.getTranslationY(), topBarHeight, contentTransY)) / (contentTransY - topBarHeight);
float downPro = (downEndY- MathUtils.clamp(dependency.getTranslationY(), contentTransY, downEndY)) / (downEndY - contentTransY);

ImageView iamgeview = child.findViewById(R.id.iv_face);
View maskView = child.findViewById(R.id.v_mask);

if (dependency.getTranslationY()>=contentTransY){
//根据Content上滑百分比位移图片TransitionY
iamgeview.setTranslationY(downProfaceTransY);
}else {
//根据Content下滑百分比位移图片TransitionY
iamgeview.setTranslationY(faceTransY+4
upPro*faceTransY);
}
//根据Content上滑百分比设置图片和蒙层的透明度
iamgeview.setAlpha(1-upPro);
maskView.setAlpha(upPro);
//因为改变了child的位置,所以返回true
return true;
}
}

其实从上面代码也可以看出逻辑非常简单,在layoutDependsOn()依赖Content,在onDependentViewChanged()里计算Content的上、下滑动百分比来处理图片和蒙层的位移、透明变化。

TopBarBehavior

这个Behavior主要处理TopBar部分的两个子View的透明度变化,

因为逻辑跟FaceBehavior十分类似就不细说了。

public class TopBarBehavior extends CoordinatorLayout.Behavior {
private float contentTransY;//滑动内容初始化TransY
private int topBarHeight;//topBar内容高度

public TopBarBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
//引入尺寸值
contentTransY= (int) context.getResources().getDimension(R.dimen.content_trans_y);
int resourceId = context.getResources().getIdentifier(“status_bar_height”, “dimen”, “android”);
int statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
topBarHeight= (int) context.getResources().getDimension(R.dimen.top_bar_height)+statusBarHeight;
}

public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
//依赖Content
return dependency.getId() == R.id.ll_content;
}

public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
//计算Content上滑的百分比,设置子view的透明度
float upPro = (contentTransY- MathUtils.clamp(dependency.getTranslationY(), topBarHeight, contentTransY)) / (contentTransY - topBarHeight);
View tvName=child.findViewById(R.id.tv_top_bar_name);
View tvColl=child.findViewById(R.id.tv_top_bar_coll);
tvName.setAlpha(upPro);
tvColl.setAlpha(upPro);
return true;
}
}

TitleBarBehavior

这个Behavior主要处理TitleBar部分在布局位置紧贴Content顶部和关联的View的透明度变化。

public class TitleBarBehavior extends CoordinatorLayout.Behavior {
private float contentTransY;//滑动内容初始化TransY
private int topBarHeight;//topBar内容高度

public TitleBarBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
//引入尺寸值
contentTransY= (int) context.getResources().getDimension(R.dimen.content_trans_y);
int resourceId = context.getResources().getIdentifier(“status_bar_height”, “dimen”, “android”);
int statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
topBarHeight= (int) context.getResources().getDimension(R.dimen.top_bar_height)+statusBarHeight;
}

public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
//依赖content
return dependency.getId() == R.id.ll_content;
}

public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
//调整TitleBar布局位置紧贴Content顶部
adjustPosition(parent, child, dependency);
//这里只计算Content上滑范围一半的百分比
float start=(contentTransY +topBarHeight)/2;
float upPro = (contentTransY-MathUtils.clamp(dependency.getTranslationY(), start, contentTransY)) / (contentTransY - start);
child.setAlpha(1-upPro);
return true;
}

public boolean onLayoutChild(@NonNull CoordinatorLayout parent, @NonNull View child, int layoutDirection) {
//找到Content的依赖引用
List dependencies = parent.getDependencies(child);
View dependency = null;
for (View view : dependencies) {
if (view.getId() == R.id.ll_content) {
dependency = view;
break;
}
}
if (dependency != null) {
//调整TitleBar布局位置紧贴Content顶部
adjustPosition(parent, child, dependency);
return true;
} else {
return false;
}
}

private void adjustPosition(@NonNull CoordinatorLayout parent, @NonNull View child, View dependency) {

最后

文章不易,如果大家喜欢这篇文章,或者对你有帮助希望大家多多点赞转发关注哦。文章会持续更新的。绝对干货!!!

  • Android进阶学习全套手册
    关于实战,我想每一个做开发的都有话要说,对于小白而言,缺乏实战经验是通病,那么除了在实际工作过程当中,我们如何去更了解实战方面的内容呢?实际上,我们很有必要去看一些实战相关的电子书。目前,我手头上整理到的电子书还算比较全面,HTTP、自定义view、c++、MVP、Android源码设计模式、Android开发艺术探索、Java并发编程的艺术、Android基于Glide的二次封装、Android内存优化——常见内存泄露及优化方案、.Java编程思想 (第4版)等高级技术都囊括其中。

  • Android高级架构师进阶知识体系图
    关于视频这块,我也是自己搜集了一些,都按照Android学习路线做了一个分类。按照Android学习路线一共有八个模块,其中视频都有对应,就是为了帮助大家系统的学习。接下来看一下导图和对应系统视频吧!!!

  • Android对标阿里P7学习视频

  • BATJ大厂Android高频面试题
    这个题库内容是比较多的,除了一些流行的热门技术面试题,如Kotlin,数据库,Java虚拟机面试题,数组,Framework ,混合跨平台开发,等

    《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
    中视频都有对应,就是为了帮助大家系统的学习。接下来看一下导图和对应系统视频吧!!!
    [外链图片转存中…(img-sGPLw2wl-1715415873852)]

  • Android对标阿里P7学习视频

[外链图片转存中…(img-6bg87zPk-1715415873852)]

  • BATJ大厂Android高频面试题
    这个题库内容是比较多的,除了一些流行的热门技术面试题,如Kotlin,数据库,Java虚拟机面试题,数组,Framework ,混合跨平台开发,等
    [外链图片转存中…(img-R80lUCiT-1715415873853)]
    《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值