1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| private ImageView img; private int xOffset = 50; private int yOffset = 10; private int continueTime = 4000; private Timer timer; private static Handler handler;
@Override @SuppressLint("HandlerLeak") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); img= (ImageView) findViewById(R.id.imageView1);
xOffset = DensityUtil.dp2px(this, xOffset); yOffset = DensityUtil.dp2px(this, yOffset); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); lp.setMargins(-xOffset, -yOffset, 0, 0); img.setLayoutParams(lp); handler = new Handler(){ @Override public void handleMessage(Message msg) { TranslateAnimation animation = null; switch (msg.what) { case 1: animation = new TranslateAnimation(0,xOffset,0, 0); break; case 2: animation = new TranslateAnimation(0,0,0, yOffset); break; } animation.setDuration(continueTime); animation.setRepeatCount(1); animation.setFillAfter(true); animation.setRepeatMode(Animation.REVERSE); img.startAnimation(animation); super.handleMessage(msg); } }; timer= new Timer(); timer.schedule(new TimerTask() { int count =1; @Override public void run() { if(count % 2 != 0){ handler.sendEmptyMessage(1); }else{ handler.sendEmptyMessage(2); } count++; } },0,continueTime*2); }
|