MPChart实现一个动态折线图

工具:MPChart库(下载地址:https://github.com/PhilJay/MPAndroidChart),Android Studio 3.1
使用教程MPChart最新版本使用教程
Xml,一个LineChart.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.github.mikephil.charting.charts.LineChart
        android:id="@+id/linechart"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

RelativeLayout>

思路:
linechart里有一个yvalues,它的元素是Entry(x,y)就是坐标点,x,y。我们只要改变x的坐标,显示后面的x坐标让后面的消失就能实现了。
代码

public class MainActivity extends AppCompatActivity {
    LineChart lineChart;
    Description description;
    LinkedList yvalues;
    int x=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lineChart=findViewById(R.id.linechart);
        yvalues=new LinkedList();
        handler.postDelayed(runnable,10);
    }
    Handler handler=new Handler();
    Runnable runnable=new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this,1000);
            x+=1;
            int y= (int) (Math.random()*10);
            yvalues.addLast(new Entry(x,y));
            if (yvalues.size()>10)
            {
                yvalues.removeFirst();
            }
            LineDataSet lineDataSet=new LineDataSet(yvalues,"line1");

            LineData lineData=new LineData(lineDataSet);
  	
 	    lineChart.setData(lineData);
            lineChart.invalidate();
        }
    };
}

你可能感兴趣的:(MPChart)