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 像素,我们希望创建一个“拉动”文本的动画,以便我们可以看到短语的结尾。
(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 Snippet 为起点:
/**
* @param view The Textview or any other view we wish to apply the movement
* @param margin A margin to take into the calculation (since the view
* might have any siblings in the same "row")
*
**/
public static Animation scrollingText(View view, float margin){
Context context = view.getContext(); //gets the context of the view
// measures the unconstrained size of the view
// before it is drawn in the layout
view.measure(View.MeasureSpec.UNSPECIFIED,
View.MeasureSpec.UNSPECIFIED);
// takes the unconstrained wisth of the view
float width = view.getMeasuredWidth();
// gets the screen width
float screenWidth = ((Activity) context).getWindowManager().getDefaultDisplay().getWidth();
// perfrms the calculation
float toXDelta = width - (screenWidth - margin);
// sets toXDelta to 0 if the text width is smaller that the screen size
if (toXDelta < 0) {toXDelta = 0; } else { toXDelta = 0 - toXDelta;}
// Animation parameters
Animation mAnimation = new TranslateAnimation(0, toXDelta, 0, 0);
mAnimation.setDuration(15000);
mAnimation.setRepeatMode(Animation.RESTART);
mAnimation.setRepeatCount(Animation.INFINITE);
return mAnimation;
}
可能有更简单的方法来执行此操作,但这适用于您可以想到的每个视图并且是可重用的。如果您想在 ListView 中为 TextView 设置动画而不破坏 textView 的启用/onFocus 功能,则它特别有用。即使视图没有聚焦,它也会连续滚动。