我设法使用ObjectAnimator为布局上的视图设置动画。
我尝试使用ObjectAnimator类在画布上制作动画,但它不起作用。 它甚至可能吗?
我所做的是创建一个扩展View的类,我像在Layout上一样定义了ObjectAnimator,然后我在画布上画了它并启动了动画(objectanimator.start)
这是代码: (//行是我的布局尝试巫婆工作)
public class MainActivity extends Activity {
SurfaceClass surface;
private ObjectAnimator anima;
//private Button but;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
surface = new SurfaceClass(this);
surface.resume();
setContentView(surface);
//but = (Button)findViewById(R.id.button1);
//anima = ObjectAnimator.ofFloat(but, "y",400);
//anima.setDuration(5000);
//anima.setRepeatCount(100);
//anima.setRepeatMode(1);
//anima.start();
}
表面:
public class SurfaceClass extends SurfaceView implements Runnable{
SurfaceHolder sHolder;
Boolean isRunning;
Thread th;
Canvas c;
Obj object;
ObjectAnimator anima;
public SurfaceClass(Context context) {
super(context);
// TODO Auto-generated constructor stub
anima = ObjectAnimator.ofFloat(object, "y",1f);
anima.setDuration(3000);
anima.setRepeatCount(100);
anima.setRepeatMode(1);
//anima.start();
object = new Obj(context);
sHolder = getHolder();
isRunning = false;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(isRunning){
if(!sHolder.getSurface().isValid())
continue;
c = sHolder.lockCanvas();
synchronized(sHolder){
doDraw(c);
}
sHolder.unlockCanvasAndPost(c);
}
}
private void doDraw(Canvas c) {
// TODO Auto-generated method stub
c.drawBitmap(object.pic, object.x, object.y, null);
anima.start();
}
public void resume() {
// TODO Auto-generated method stub
isRunning = true;
th = new Thread(this);
th.start();
}
}
对象:
public class Obj extends View {
float x = 200,y=30;
Bitmap pic;
public Obj(Context context) {
super(context);
// TODO Auto-generated constructor stub
pic = BitmapFactory.decodeResource(getResources(), R.drawable.cat_trance);
}
public void setY(float f){
y=f;
}
public float getY(){
return y;
}
}
答案 0 :(得分:0)
试试这个,
@Override
protected void onAttachedToWindow(){
anima.start();
}
并删除anima.start();
方法中的doDraw
。