安卓图表的简单介绍
一、MPAndroidChart
MPAndroidChart 是一款开源的强大的图表库。支持折线图、饼图、柱状图、散点图网状图等,支持 Android 2.2 以上,支持横纵轴缩放,多指缩放,展现动画、高亮、保存到 sdcard、从文件读取图表。
官方项目地址:https://github.com/PhilJay/MPAndroidChart
1.添加依赖方式
第一种:
Gradle Setup
Project 的build.gradle文件中添加
repositories {
maven {
url 'https://jitpack.io' }
}
在 module中的build,gradle 中添加
dependencies {
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}
Maven Setup
<!-- <repositories> section of pom.xml -->
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
<!-- <dependencies> section of pom.xml -->
<dependency>
<groupId>com.github.PhilJay</groupId>
<artifactId>MPAndroidChart</artifactId>
<version>v3.1.0</version>
</dependency>
第二种:
【简单粗暴】本地导入依赖
下载MPAndroidChart-v3.0.3.jar
链接:https://pan.baidu.com/s/1tbjKVE_IMWudjLEiq3bXcg
提取码:g4yy
下载完后将包导入lib文件夹下,如下图
无论是 哪一种方法,添加后,点击sync按钮【小象图标】
2.折线图
①建一个布局文件
<com.github.mikephil.charting.charts.LineChart
android:id="@+id/line"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.github.mikephil.charting.charts.LineChart>
②建一个LineChartActivity.java,需要完成创建一个list用来保存数据,对折线的形状、颜色等进行设计,导入数据以及最后实例化Dataset 。
import android.os.Bundle;
import android.view.WindowManager;
import com.github.mikephil.charting.data.Entry;
import androidx.appcompat.app.AppCompatActivity;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Color;
public class LineChartActivity extends AppCompatActivity {
//①实例化一个 List 用来保存你的数据
private LineChart line;
List<Entry>list=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.linechart);
setTitle("LineChartActivity");
//②findViewById方法获取到布局文件中的元素
line = (LineChart) findViewById(R.id.line);
//③line Style
// background color
line.setBackgroundColor(Color.WHITE);
// disable description text
line.getDescription().setEnabled(false);
// enable touch gestures
line.setTouchEnabled(true);
// enable scaling and dragging
line.setDragEnabled(true);
line.setScaleEnabled(true);
// line.setScaleXEnabled(true);
// line.setScaleYEnabled(true);
// force pinch zoom along both axis
line.setPinchZoom(true);
//④导入数据
//其中两个数字对应的分别是 X轴Y轴
list.add(new Entry(0,90));
list.add(new Entry(1,95));
list.add(new Entry(2,87));
list.add(new Entry(3,99));
list.add(new Entry(4,100)