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像素。我们有一个TextView,其文本宽度为700px,我们希望创建一个动画来“拉”文本,以便我们可以看到短语的结尾。
(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值。为了达到理想的效果,我们需要将文本“拉”出与屏幕完全相同的px。(在方案中用<<<< X px >>>>表示)由于我们的文本宽度为700,可见区域为320px(屏幕宽度),因此我们设置:
tXDelta = 700 - 320 = 380
以及我们如何计算屏幕宽度和文本宽度?
码
以Zarah片段为起点:
/**
* @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的enabled / onFocus功能,则它特别有用。即使视图未聚焦,它也会连续滚动。