我想动画一个简单的视图,例如简单的textview。我想使用translate为视图设置动画。
现在我的要求是,我想制作一个方法,例如slide(View v, float position)
。这将使视图动画并定位到应该动画的位置。我会在代码中的所需位置调用该方法。
为了做到这一点,我尝试了一些东西。我已将MyTranslateAnimation
课程改为如下。
public class MyTranslateAnimation extends Animation {
private View mView;
private final float position;
public MyTranslateAnimation(View view, float position){
mView = view;
this.position = position;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
mView.setY(position);
mView.requestLayout();
}
}
然后我在textview
中设置MainActivity.java
并设置onTouchListener
,然后创建此方法slide()
以执行上述任务。
以下是代码:
onCreate():
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_root = (ViewGroup)findViewById(R.id.root);
_view = new TextView(this);
_view.setText("TextView!!!!!!!!");
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(150, 50);
layoutParams.leftMargin = 50;
layoutParams.topMargin = 50;
layoutParams.bottomMargin = -250;
layoutParams.rightMargin = -250;
_view.setLayoutParams(layoutParams);
_view.setOnTouchListener(this);
_root.addView(_view);
}
slide():
private void slide(View view, float position){
Animation animation = new MyTranslateAnimation(view, position);
animation.setInterpolator(new DecelerateInterpolator());
animation.setDuration(200);
animation.start();
}
如下所示,我使用了slide()
方法:
public boolean onTouch(View view, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
slide(view, 100);
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
view.setLayoutParams(layoutParams);
break;
}
_root.invalidate();
return true;
}
此外,我还不想使用nineoldandroid
库。
对此有任何帮助表示高度赞赏。