TranslateAnimation通过指定的量在一个方向上"拉动"视图。您可以设置从哪里开始这种"拉动"和结束在哪里。
TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta);
fromXDelta设置X轴上移动的起始位置偏移量。
fromXDelta = 0 //no offset.
fromXDelta = 300 //the movement starts at 300px to the right.
fromXDelta = -300 //the movement starts at 300px to the left
toXDelta 定义在 X 轴上移动的结束位置偏移量。
toXDelta = 0 //no offset.
toXDelta = 300 //the movement ends at 300px to the right.
toXDelta = -300 //the movement ends at 300px to the left.
如果文本宽度大于 fromXDelta 和 toXDelta 之间差的绝对值,那么该文本将无法完全在屏幕内移动。
示例
假设我们的屏幕尺寸为320x240像素。我们有一个带有700像素宽度文本的TextView,并希望创建一个“拉”文本的动画,以便我们可以看到短语的结尾。
(screen)
+---------------------------+
|<----------320px---------->|
| |
|+---------------------------<<<< X px >>>>
movement<-----|| some TextView with text that goes out...
|+---------------------------
| unconstrained size 700px |
| |
| |
+---------------------------+
+---------------------------+
| |
| |
<<<< X px >>>>---------------------------+|
movement<----- some TextView with text that goes out... ||
---------------------------+|
| |
| |
| |
+---------------------------+
首先,我们将fromXDelta = 0
以确保动画没有起始偏移量。现在,我们需要确定toXDelta
的值。为了实现所需的效果,我们需要将文本“拉出”与屏幕宽度相同的像素数(在该方案中由<<<< X px >>>>表示)。由于我们的文本宽度为700,而可见区域为320px(屏幕宽度),因此我们设置:
tXDelta = 700 - 320 = 380
我们该如何确定屏幕宽度和文本宽度呢?
代码
以Zarah代码段为起点:
public static Animation scrollingText(View view, float margin){
Context context = view.getContext();
view.measure(View.MeasureSpec.UNSPECIFIED,
View.MeasureSpec.UNSPECIFIED);
float width = view.getMeasuredWidth();
float screenWidth = ((Activity) context).getWindowManager().getDefaultDisplay().getWidth();
float toXDelta = width - (screenWidth - margin);
if (toXDelta < 0) {toXDelta = 0; } else { toXDelta = 0 - toXDelta;}
Animation mAnimation = new TranslateAnimation(0, toXDelta, 0, 0);
mAnimation.setDuration(15000);
mAnimation.setRepeatMode(Animation.RESTART);
mAnimation.setRepeatCount(Animation.INFINITE);
return mAnimation;
}
可能有更简单的方法来实现这个功能,但这种方法适用于您能想到的每个视图,而且可以重复使用。如果您想在ListView中动画化TextView而不破坏textView的启用/焦点能力,则此方法尤其有用。即使该视图未获得焦点,它也会持续滚动。