Graphview для android studio

Библиотека GraphView

Библиотека для построения графиков двух видов.

Официальная страница

Готовую библиотеку можно скачать по адресу http://android-graphview.org/. Также есть страница на Гитхабе с открытыми исходниками.

Работаем с библиотекой

Скопируем библиотеку в папку libs вашего проекта.

Подключение происходит следующим образом. Вы создаёте макет экрана на основе LinearLayout и программно подключаете нужный класс к данному контейнеру.

Осталось написать код для активности. Нужно указать данные для графика, а компонент постарается автоматически вычислить доступный ему размер и пропорционально разместить данные для сетки, а затем нарисует график. Начнём с линейной графики.

Чтобы линейный график заменить на гистрограмму (или как он там называется?), то нужно заменить класс LineGraphView на BarGraphView:

На графике видно, что понедельник — день тяжёлый и кот поймал только три мышки. Потом обычные трудовые будни, в пятницу кот уже ждёт предстоящих выходных и работает спустя рукава. Ну а в субботу и воскресенье он отказывается работать, ссылаясь на трудовой кодекс и угрожая пожаловаться в Общество защиты животных. Бездельник!

Также существуют различные методы для управления стилями: цветом, размерами и т.п. Примеры можно посмотреть на сайте автора.

Источник

Create a real time line graph in Android with GraphView

In Android applications, there are a lot of use cases in which you must create graphs. Fortunately, a lot of open source libraries exist letting you to easily create line graphs, bar graphs or other style of graphs. These libraries have the main advantages to be designed entirely for Android and so, they are optimized.

Among the main libraries, we’re going to try three of them :

  • GraphView
  • AChartEngine
  • MP Android Chart

To test these libraries, we’re going to try to create a real time graph in Android. In this first article, we’re going to use GraphView.

Читайте также:  Фар плеер для андроид

GraphView is an open source library available on GitHub : https://github.com/jjoe64/GraphView

GraphView has also an interesting website with a great documentation : http://www.android-graphview.org

In this tutorial, we use Eclipse so we must download the library as a jar file in version 4.0.0 and add it in libs folder of our Android application project. First step is to add the GraphView in a layout XML file :

Then, we can use it in an Activity like this :

In this code, we get GraphView instance defined in the layout file. Then, we define data that will be displayed thanks to LineGraphSeries class. So, we choose to display a line graph. Each data is designed inside a DataPoint class. Method addEntry lets to add new entries to graph’s data.

To simulate real time data addition, we create a thread that add data to the LineGraphSeries dataset and then we make a sleep in the thread. To update UI state in the UI thread, we put the addEntry call in a runOnUiThread method.

Thanks to GraphView, we have created a real time line graph on Android. However, if result works well, the rendering is not very beautiful. We will try to get a better rendering with AChartEngine or MP Android Chart in next tutorials.

You can also check this Youtube video that show live coding of this tutorial :

Источник

Graphview для android studio

Chart and Graph Library for Android

Project maintainer wanted! For time reasons I can not continue to maintain GraphView. Contact me if you are interested and serious about this project. g.jjoe64@gmail.com

What is GraphView

GraphView is a library for Android to programmatically create flexible and nice-looking diagrams. It is easy to understand, to integrate and to customize.

Supported graph types:

  • Line Graphs
  • Bar Graphs
  • Point Graphs
  • or implement your own custom types.
Читайте также:  Panasonic android tv tx 43gxr600 телевизор

  • Line Chart, Bar Chart, Points
  • Combination of different graph types
  • Scrolling vertical and horizontal . You can scroll with a finger touch move gesture.
  • Scaling / Zooming vertical and horizontal . With two-fingers touch scale gesture (Multi-touch), the viewport can be changed.
  • Realtime Graph (Live change of data)
  • Second scale axis
  • Draw multiple series of data . Let the diagram show more that one series in a graph. You can set a color and a description for every series.
  • Show legend . A legend can be displayed inline the chart. You can set the width and the vertical align (top, middle, bottom).
  • Custom labels . The labels for the x- and y-axis are generated automatically. But you can set your own labels, Strings are possible.
  • Handle incomplete data . It’s possible to give the data in different frequency.
  • Viewport . You can limit the viewport so that only a part of the data will be displayed.
  • Manual Y axis limits
  • And much more. Check out the project page and/or the demo app

Download Demo project at Google Play Store

More examples and documentation

To show you how to integrate the library into an existing project see the GraphView-Demos project! See GraphView-Demos for examples. https://github.com/jjoe64/GraphView-Demos
View GraphView wiki page https://github.com/jjoe64/GraphView/wiki

About

Android Graph Library for creating zoomable and scrollable line and bar graphs.

Источник

androidsubway

android tips & tricks

GraphView Library Tutorial in Android

Let’s we create Graph in Android with the help of GraphView .
Step 1) First we create new project in Android studio Name is ” GraphViewExample”
then, download the androidGraphView library jar file.
GraphView-4.0.1.jar
#Important:- The jar file does not support xml integration

Step 2) Copy the .jar file and paste it into lib folder

Step 3) 1-Go File tab and select Project Structure for lib dependency

2-Go Dependency tab , select File dependency and add lib .jar file or press OK

Читайте также:  Compile java code android

Step 4) After that , Update”activity_main.xml”

Step 5) Then , Update “MainActivity.java”
[Code language=”java”]GraphView graph = (GraphView) findViewById(R.id.graph);
BarGraphSeries series = new BarGraphSeries(new DataPoint[] <
new DataPoint(0, 5),
new DataPoint(2, 5),
new DataPoint(3, 0),
new DataPoint(4, 2),
new DataPoint(4, 6)
>);
graph.addSeries(series);

// styling-add color
series.setValueDependentColor(new ValueDependentColor() <
@Override
public int get(DataPoint data) <
return Color.rgb((int) data.getX() * 255 / 4, (int) Math.abs(data.getY() * 255 / 6), 100);
>
>);

//draw values on top
series.setDrawValuesOnTop(true);
series.setValuesOnTopColor(Color.RED);
series.setValuesOnTopSize(50);

Result-

Источник

Как интегрировать GraphView в мой проект?

Поэтому я искал графическое решение для своего приложения, и я наткнулся на GraphView .

Я смотрел на github и в исходных файлах, и я не могу найти руководство по интеграции. Может быть, это прямо перед моим лицом, но я ничего не вижу.

Я никогда раньше не комментировал код elses, поэтому, если бы кто-нибудь мог быстро рассказать о том, как интегрировать GraphView с моим текущим проектом, я был бы очень признателен.

  1. Возьмите здесь библиотечную банку.
  2. Скопируйте эту банку в папку /libs в проекте, где вы хотите использовать GraphView .
  3. используй это.

Получите проект из github используя git :

  • Перейдите в свой любимый каталог, используя git bash
  • Выполнить из git git clone git://github.com/jjoe64/GraphView.git graphView
  • В File Eclipse -> Import. -> Android – / Existing Android Code Into Project (используйте Browse чтобы перейти к папке graphView из вашей любимой папки предыдущего шага)
  • Щелкните правой кнопкой мыши проект, который будет использовать GraphView -> Properties -> Android -> внизу (область Library ), с помощью Add. чтобы выбрать GraphView
  • используй это

GraphView был добавлен в Maven Central, поэтому интеграция с Android Studio стала еще проще. Просто добавьте следующее в свой файл build.gradle, и вам не нужно загружать .jar.

В Android Studio добавьте эту строку в файл build.gradle:

И не забудьте нажать «Sync project with Gradle files».

Ответ с использованием студии Android:
– скачать .jar из этой ссылки

Источник

Оцените статью