Use a GraphView in a Fragment

From what I’ve seen, most tutorials relative to GraphView use direct Actions. I wanted to use a Fragment instead. Here are the steps I did (using the Android Studio):

Create a Layout Fragment

First, create a fragment (create a new Layout Resource File), based on a LinearLayout. I ended up with a file named fragment_graph.xml with the following content:

The idea is pretty simple; the widget to be used by the Graph is graph1.

Create the Java Fragment

On the java side, I’ve added a new class GraphFragment which extends the Fragment class:

This is a pretty standard fragment. The secret sauce is in the populateGraphView() method. Here, we perform three operations:



  • First, we create the data set:

    We do the dataset initialisation here because it’s an example. You may want to do it somewhere else if you collect it off a remote service for example.

  • Build the GraphView:

    and add the dataset:

    The Activity required by the GraphView constructor (in this case LineGraphView) can be collected form the Fragment instance via getActivity().

  • Get the widget reference in the fragment and add the GraphView to it:


    pre lang=”java>try {
    LinearLayout layout = (LinearLayout) view.findViewById(;
    } catch (NullPointerException e) {
    // something to handle the NPE.

    Incidentally, is our graph1 from the layout file.

  • The full code of the class is:

    Add the Fragment to an Activity

    Once the fragment is defined, all that’s left to be done is to add it to an activity. If you have a sample activity-based project, you can end up with a layout file (activity_fragments.xml) similar to this:

    Simple, isn’t it?


    A little experiment: If you find this post and ad below useful, please check the ad out :-)

    6 thoughts on “Use a GraphView in a Fragment

    1. thx for ur tutorial. for me i don’t know wats missing ,because i am using a pageviewer and my app is not even starting , please can u give the whole code.

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Scroll to top