如何实现TextView在窗口边距内的平移入场退场动画
实现TextView从左侧边距后出现、右侧边距消失的平移动画(无复杂遮罩)
不用复杂遮罩完全可行,核心是避免硬编码偏移值,而是基于TextView自身宽度和父布局的实际尺寸计算动画的起始/结束位置,或者使用相对位置参数适配所有屏幕。
问题原因
你之前的代码用了固定的-1000和1000作为偏移量,会导致:
- 不同尺寸屏幕上效果不一致
- 无法精准对应父布局边距,可能出现TextView未完全移出或提前消失的情况
解决方案1:动态计算绝对偏移值(适配父布局)
通过获取TextView和父布局的实际宽度,计算出刚好让TextView从左侧完全隐藏到右侧完全隐藏的偏移量:
TextView tv = findViewById(R.id.textview); tv.setText("101010010101000110101010101"); final int animationDuration = 3000; // 必须等View完成测量后再获取宽度,否则会得到0 tv.post(() -> { View parentContainer = (View) tv.getParent(); int parentWidth = parentContainer.getWidth(); int textViewWidth = tv.getWidth(); // 起始位置:TextView完全在父布局左侧外(X坐标为负的自身宽度) float fromXDelta = -textViewWidth; // 结束位置:TextView完全在父布局右侧外(X坐标等于父布局宽度) float toXDelta = parentWidth; TranslateAnimation animator = new TranslateAnimation(fromXDelta, toXDelta, 0, 0); animator.setDuration(animationDuration); animator.setRepeatCount(ValueAnimator.INFINITE); animator.setRepeatMode(ValueAnimator.RESTART); tv.startAnimation(animator); });
解决方案2:使用相对位置参数(更简洁适配)
利用TranslateAnimation的相对构造方法,直接基于自身和父布局的比例设置偏移,无需手动计算宽度:
TextView tv = findViewById(R.id.textview); tv.setText("101010010101000110101010101"); final int animationDuration = 3000; TranslateAnimation animator = new TranslateAnimation( Animation.RELATIVE_TO_SELF, -1.0f, // 起始X:相对于自身宽度,向左偏移100%(完全隐藏在左侧外) Animation.RELATIVE_TO_PARENT, 1.0f, // 结束X:相对于父布局宽度,向右偏移100%(完全隐藏在右侧外) Animation.RELATIVE_TO_SELF, 0.0f, // Y轴无偏移 Animation.RELATIVE_TO_SELF, 0.0f ); animator.setDuration(animationDuration); animator.setRepeatCount(ValueAnimator.INFINITE); animator.setRepeatMode(ValueAnimator.RESTART); tv.startAnimation(animator);
说明
两种方案都能实现:
- 动画开始时,TextView完全隐藏在父布局左侧边距后方
- 移动过程中逐渐进入屏幕、完全显示后再逐渐移出
- 动画结束时,TextView完全隐藏在父布局右侧边距后方
全程不需要任何遮罩或复杂几何处理。
内容的提问来源于stack exchange,提问作者slowcoder
相关产品推荐
相关产品推荐

