使用RotateDrawable,Thread和 Handler实现仪表盘指针旋转功能
1》RotateDrawable资源文件res/drawable/rotate_pointer.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/img_pointer"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360">
</rotate>
2》布局如下:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ImageView
android:id="@+id/img_iv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/rotate_pointer"
android:background="@drawable/img_bg"/>
</RelativeLayout>
效果如下:
3》代码如下:
package com.demo.cxc.drawabledemo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final String PROGRESS_KEY = "MainActivity.progress_key";
private ImageView img_iv;
private Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
TODO: 15/6/8
//
int progress = msg.getData().getInt(PROGRESS_KEY);
Log.d(TAG, "****thread:" + Thread.currentThread().getId() + "----receive:" + progress);
img_iv.setImageLevel((int) (progress * 10000.0 / 100));
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
//启到一个新线程
new Thread(backgroundThreadRunnable).start();
}
private void initViews() {
img_iv = (ImageView) findViewById(R.id.img_iv);
}
private Runnable backgroundThreadRunnable = new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
Message msg = myHandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putInt(PROGRESS_KEY, i);
//设置要传递的数据
msg.setData(bundle);
//发送数据
msg.sendToTarget();
Log.d(TAG, "----thread:" + Thread.currentThread().getId() + "----send:" + i);
try {
Thread.sleep(200);//休眠200ms
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
}
这样当程序运行时,中间的指针就可以根据后台线程发送过来的数据来旋转,以实现仪表盘的功能。