【Animation】 使用handler和Runnable实现某一个控件的抖动效果


布局:

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    android:background="#000000">



   

	<Button android:layout_width="wrap_content"

	    android:layout_height="wrap_content"

	    android:id="@+id/btn"

	    android:text="Hello!"/>

</LinearLayout>



代码:   使用handler的postDelayed方法每半秒钟发送一个消息来执行动画效果,同时在handler里面使动画平移的距离缩短,当距离为零时就通过handler的 removeCallbacks方法取消runnable正在执行的操作每一次点击按钮都重置一下动画的距离,并且开启runnable,执行操作!

 

 

package com.example.viewpager;



import android.app.Activity;

import android.os.Bundle;

import android.os.Handler;

import android.util.Log;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.animation.TranslateAnimation;

import android.widget.Button;



public class MainActivity extends Activity {

	private Button btn;

	private int length;

	Handler handler = new Handler(){

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {

			case 0:

				length -= 2.5;

				TranslateAnimation animation = new TranslateAnimation(0,length , 0, 0);

				animation.setDuration(50);

				Log.i("----", length+"");

				btn.startAnimation(animation);

				if(length==0){

					handler.removeCallbacks(runnable);

				}

				break;



			default:

				break;

			}

		};

	};

	Runnable runnable = new Runnable() {

		public void run() {

			handler.sendEmptyMessage(0);

			handler.postDelayed(this, 80);

		}

	};

	@Override

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

		btn = (Button) findViewById(R.id.btn);

		btn.setOnClickListener(new OnClickListener() {

			@Override

			public void onClick(View v) {

				length = 30;

				handler.post(runnable);

			}

		});

	}

	@Override

	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.

		getMenuInflater().inflate(R.menu.main, menu);

		return true;

	}



}



你可能感兴趣的:(animation)