在android的開發(fā)過程中,需要使用圖表,圖表有第三方的插件實(shí)現(xiàn)了該功能。目前有很多類似的功能插件,比如achartengine, Graphview等等。Graphview比較簡(jiǎn)潔,用起來簡(jiǎn)單,目前支持折線圖和條形圖圖表樣式。其他目前還沒有用過,今天的學(xué)習(xí)基于Graphview。
在項(xiàng)目中導(dǎo)入Graphview源碼模塊
如何導(dǎo)入可參考文章:013android初級(jí)篇之Android Studio 引用源碼模塊,jar及so文件
第一個(gè)簡(jiǎn)單程序
布局文件
<com.jjoe64.graphview.GraphView
android:layout_width="match_parent"
android:layout_height="200dip"
android:id="@+id/graph" />
代碼
graph = (GraphView) findViewById(R.id.graph);
LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(new DataPoint[] {
new DataPoint(0, 1),
new DataPoint(1, 5),
new DataPoint(2, -1),
new DataPoint(3, 10),
new DataPoint(4, 6),
new DataPoint(5, 8),
new DataPoint(4, 5)
});
graph.addSeries(series);
顯示的圖表橫軸和縱軸的值會(huì)根據(jù)輸入的數(shù)據(jù)而變化。
動(dòng)態(tài)修改數(shù)據(jù)
Graphview中提供了兩個(gè)接口來動(dòng)態(tài)修改數(shù)據(jù)
resetData(DataPoint[] )
這個(gè)方法將重置數(shù)據(jù),使用新的數(shù)據(jù)替代。-
public void appendData(E dataPoint,boolean scrollToEnd,int maxDataPoints)
dataPoint - values the values must be in the correct order! x-value has to be ASC. First the lowest x value and at least the highest x value.
scrollToEnd - true => 數(shù)據(jù)顯示的方向,是否從MaxX開始
maxDataPoints - 保留的最多的數(shù)據(jù)節(jié)點(diǎn)個(gè)數(shù)
基本思想是
從加速傳感器中獲得動(dòng)態(tài)數(shù)據(jù);
-
在ui主線程中更新此數(shù)據(jù)
graph.addSeries(series);
graph.getViewport().setScalable(false);
graph.setTitle("加速計(jì)");
graph.getViewport().setMinX(0);
graph.getViewport().setMaxX(200);graph.getViewport().setMinY(0);
graph.getViewport().setMaxY(30);
graph.getViewport().setYAxisBoundsManual(true);
graph.getViewport().setYAxisBoundsManual(true);
利用Timer 定時(shí)更新數(shù)據(jù):
timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Message msg=mHandler.obtainMessage();
msg.what=1;
mHandler.sendMessage(msg);
}
},500,COLLECT_TIME);
使用后handle處理調(diào)用更新數(shù)據(jù):
mHandler = new Handler(){
@Override
public void handleMessage(Message msg){
super.handleMessage(msg);
DataPoint[] values = new DataPoint[1];
values[0] = new DataPoint(x,a);
x++;
series.appendData(values[0],true,200);
}
};
具體的定制,請(qǐng)參考鏈接中的相關(guān)資料