Use a GraphView in a Fragment

Posted by in Software

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:

<

ol>

  • 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(R.id.graph1);
    layout.addView(graphView);
    } catch (NullPointerException e) {
    // something to handle the NPE.
    }

    Incidentally, R.id.graph1 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?

    HTH,


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