android:仪表盘(简单易实现)

来源:互联网 发布:淘宝运费险保费 编辑:程序博客网 时间:2024/05/20 08:25

开发的应用中需要实现一个仪表盘功能,上网找了一些代码,看起来有点麻烦,于是自己研究了一下,实现了这个仪表盘。

这个仪表盘的主要实现就在于以下这两张图片:

这两张图片其实是两个同心的正方形(周围都是透明的)。使用RelativeLayout控制它们中心重合,这样就可以简单以中心为圆心转动。

下面是实现代码:

MainActivity.java

package zwp.instrument;import java.util.Timer;import java.util.TimerTask;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.animation.Animation;import android.view.animation.RotateAnimation;import android.widget.ImageView;import android.app.Activity;public class MainActivity extends Activity {private ImageView needleView;  //指针图片private Timer timer;  //时间private float degree = 0.0f;  //记录指针旋转private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {  //设置仪表盘指针转动动画//仪表盘最大是172度,这个是自己测出来的if (degree >= 172.0f) {timer.cancel();}degree += 2.0f;RotateAnimation animation = new RotateAnimation(degree, degree, Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f);animation.setDuration(1000);animation.setFillAfter(true);needleView.startAnimation(animation);}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);needleView = (ImageView) findViewById(R.id.needle);// 开始转动timer = new Timer();// 设置每一秒转动一下timer.schedule(new NeedleTask(), 0, 1000);}private class NeedleTask extends TimerTask {@Overridepublic void run() {handler.sendEmptyMessage(0);}}}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content" >        <ImageView        android:layout_width="270dp"    android:layout_height="270dp"    android:src="@drawable/panel"    android:layout_centerHorizontal="true"    android:layout_marginTop="20dp"/>        <ImageView        android:id="@+id/needle"    android:layout_width="270dp"    android:layout_height="270dp"    android:layout_centerHorizontal="true"    android:layout_marginTop="20dp"    android:src="@drawable/needle" />    </RelativeLayout>


这样就简单的实现了一个仪表盘。

Demo下载地址:http://download.csdn.net/detail/syaringan356/6014021