管理自定义X轴 - AChartEngine

时间:2014-04-22 13:42:52

标签: android graph achartengine

我想像yaxis中发生的那样自动管理xaxis标签。

我使用addTextLabel作为我的xaxis标签。

public class HomeFragment extends Fragment {

//Development URL
private static String url = "http://192.168.0.100/jsontraining/production.json";

//Y-Values
private static ArrayList<HashMap<String, ArrayList<Long>>> jsonlist = new ArrayList<HashMap<String, ArrayList<Long>>>();
private static HashMap<String, ArrayList<Long>> mapValues = new HashMap<String, ArrayList<Long>>();

//Legends
private static ArrayList<HashMap<String, String>> jsonListString = new ArrayList<HashMap<String, String>>();
private static HashMap<String, String> mapValuesText = new HashMap<String,String>();

private static ArrayList<String> dateStringArray = new ArrayList<String>();

private GraphicalView chartView;

public HomeFragment(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    new JSONParse().execute();
    return rootView;
}

@SuppressWarnings("unchecked")
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onResume() {
    super.onResume();
    jsonlist.clear();
    mapValues.clear();
}

private class JSONParse extends AsyncTask<String, String, JSONObject>
{
    private ProgressDialog pDialog;
    @Override
    protected void onPreExecute() 
    {
        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Getting Data ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }//End of onPreExecute

    @Override
    protected JSONObject doInBackground(String... args) 
    {
        JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromUrl(url);
        return json;
    }//End of doInBackground

    @Override
    protected void onPostExecute(JSONObject json) 
    {
        pDialog.dismiss();
        try 
        {
            //Fetching Array of Elements
            JSONArray jsonArray = json.getJSONArray("elements");

            //Fetching for TextView
            //Fetching for Pertamina EP
            TextView uid;
            uid = (TextView) getActivity().findViewById(R.id.txtLabel);
            JSONObject jsonElementsText = jsonArray.getJSONObject(jsonArray.length()-1);
            String text = jsonElementsText.getString("text");
            //Fetching for Date
            JSONObject jsonObjectXAxis = json.getJSONObject("x_axis");
            JSONObject jsonObjectXAxisLabels = jsonObjectXAxis.getJSONObject("labels");
            JSONArray jsonArrayXAxisLabels = jsonObjectXAxisLabels.getJSONArray("labels");
            for(int i=0;i<jsonArrayXAxisLabels.length();i++)
            {
                dateStringArray.add((String) jsonArrayXAxisLabels.getString(i));
            }
            String jsonArrayStringXAxisLabels = (String) jsonArrayXAxisLabels.getString(jsonArrayXAxisLabels.length()-1);
            //JSON String to Date Format
            char[] dateChar = jsonArrayStringXAxisLabels.toCharArray();
            String day = ""+dateChar[0]+""+dateChar[1]+"";
            String monthNo = ""+dateChar[3]+""+dateChar[4]+"";
            if(monthNo.matches("01"))
            {
                monthNo="January";
            }
            if(monthNo.matches("01"))
            {
                monthNo="January";
            }
            if(monthNo.matches("02"))
            {
                monthNo="February";
            }
            if(monthNo.matches("03"))
            {
                monthNo="March";
            }
            if(monthNo.matches("04"))
            {
                monthNo="April";
            }
            if(monthNo.matches("05"))
            {
                monthNo="May";
            }
            if(monthNo.matches("06"))
            {
                monthNo="June";
            }
            if(monthNo.matches("07"))
            {
                monthNo="July";
            }
            if(monthNo.matches("08"))
            {
                monthNo="August";
            }
            if(monthNo.matches("09"))
            {
                monthNo="September";
            }
            if(monthNo.matches("10"))
            {
                monthNo="October";
            }
            if(monthNo.matches("11"))
            {
                monthNo="November";
            }
            if(monthNo.matches("12"))
            {
                monthNo="December";
            }
            Time today = new Time(Time.getCurrentTimezone());
            today.setToNow();
            int year = today.year;
            //Fetching for Number
            JSONArray jsonArrayValues = jsonElementsText.getJSONArray("values");
            Long arrayValuesMax = jsonArrayValues.getLong(jsonArrayValues.length()-1);

            //Fetching to Text View
            //uid.setText("Total produksi minyak "+text+", "+day+" "+monthNo+" "+year+" = "+arrayValuesMax+" BBLs");
            uid.setText(Html.fromHtml("Total produksi minyak <b>"+text+"</b>, "+day+" "+monthNo+" "+year+" = <b>"+NumberFormat.getNumberInstance(Locale.GERMAN).format(arrayValuesMax)+"</b> BBLs"));
            JSONObject jsonYAxis = json.getJSONObject("y_axis");
            Long yAxisMin = jsonYAxis.getLong("min");
            Long yAxisMax = jsonYAxis.getLong("max");

            for (int i=0;i<jsonArray.length();i++) 
            {
                ArrayList<Long> list = new ArrayList<Long>();
                HashMap<String, ArrayList<Long>> mapValues = new HashMap<String, ArrayList<Long>>();
                JSONObject elementNo = (JSONObject) jsonArray.get(i);
                JSONArray valuesGraph = (JSONArray) elementNo.get("values");
                String texts = elementNo.getString("text");

                int len = valuesGraph.length();
                for (int x=0;x<len;x++)
                {
                    if(!valuesGraph.isNull(x))
                    {
                        Long nilai = (Long)valuesGraph.getLong(x);
                        list.add(nilai);
                    }
                }
                mapValues.put("Values", list); 
                mapValuesText.put("Text", texts);

                jsonlist.add(mapValues);
                jsonListString.add(mapValuesText);
            }

            //Line Graph
            XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

            XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();

            mRenderer.setApplyBackgroundColor(true);
            mRenderer.setBackgroundColor(Color.rgb(254, 254, 254));
            mRenderer.setMarginsColor(Color.rgb(254, 254, 254));



            int[] x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};

            for(int start=0; start<jsonlist.size(); start++)
            {
                start++;
                mapValuesText = jsonListString.get(start-1);
                TimeSeries series = new TimeSeries(mapValuesText.get("Text").trim());
                start--;
                mapValues = jsonlist.get(start);
                int jumlahValues = mapValues.get("Values").size();

                for(int i=0; i<jumlahValues; i++)
                {
                    series.add(x[i], mapValues.get("Values").get(i));
                }
                dataset.addSeries(series);
                XYSeriesRenderer renderer = new XYSeriesRenderer();
                renderer.setShowLegendItem(true);
                renderer.setChartValuesTextSize(24);
                renderer.setColor(Color.rgb(0,108,183));
                renderer.setLineWidth(3);
                renderer.setPointStyle(PointStyle.CIRCLE);
                renderer.setFillPoints(true);
                //renderer.setDisplayChartValues(true);
                mRenderer.addSeriesRenderer(renderer);
            }



            //XY Titles
            mRenderer.setYTitle("Production");
            //mRenderer.setXTitle("Date");
            mRenderer.setAxisTitleTextSize(22);
            mRenderer.setLabelsTextSize(22);
            mRenderer.setXLabelsColor(Color.BLACK);
            mRenderer.setYLabelsColor(0, Color.BLACK);
            mRenderer.setShowLabels(true);

            //Legends
            mRenderer.setShowLegend(true);
            //mRenderer.setFitLegend(true);
            mRenderer.setLegendTextSize(20);
            mRenderer.setXLabelsPadding(20);

            mRenderer.setYLabelsAlign(Align.RIGHT, 0);
            mRenderer.setYLabelsPadding(7);
            mRenderer.setYLabelsVerticalPadding(-5);

            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) 
            {
                for (int i = 0; i < jsonArrayXAxisLabels.length();) 
                { 
                    String xChartDates = jsonArrayXAxisLabels.getString(i);
                    mRenderer.addTextLabel(i+1, xChartDates);
                    if(mapValues.get("Values").size()<9)
                    {
                        i=i+1;
                    }
                    else
                    {
                        i=i+4;
                    }
                }
                mRenderer.setXLabelsAlign(Align.CENTER);
                mRenderer.setXLabels(0);
            } else {
                for (int i = 0; i < jsonArrayXAxisLabels.length(); i++) 
                { 
                    String xChartDates = jsonArrayXAxisLabels.getString(i);
                    mRenderer.addTextLabel(i+1, xChartDates);
                }
                mRenderer.setXLabelsAlign(Align.CENTER);
            }

            mRenderer.setAxesColor(Color.BLACK);
            mRenderer.setLabelsColor(Color.BLACK);
            mRenderer.setMargins(new int[]{ 10, 110, 10, 10});
            mRenderer.setYAxisMax(yAxisMax);
            mRenderer.setYAxisMin(yAxisMin);
            mRenderer.setXAxisMin(0);
            mRenderer.setXAxisMax(jsonArrayXAxisLabels.length());
            mRenderer.setRange(new double[] { 0, jsonArrayXAxisLabels.length(), yAxisMin, yAxisMax });
            mRenderer.setPointSize(9.5f);
            //mRenderer.setPanLimits(new double[]{0, (jsonArrayXAxisLabels.length())*1.1, yAxisMin, yAxisMax});
            mRenderer.setInScroll(true);
            mRenderer.setClickEnabled(true);
            mRenderer.setZoomButtonsVisible(true);

            //Grid
            mRenderer.setShowGrid(true);
            //mRenderer.setShowGridX(true);
            //mRenderer.setShowGridY(true);
            //mRenderer.setXLabels(4);
            mRenderer.setShowCustomTextGrid(true);
            mRenderer.setGridColor(Color.rgb(162,172,186));

            if(chartView!=null)
            {
                chartView.repaint();
            }
            else{
                chartView = ChartFactory.getLineChartView(getActivity(), dataset, mRenderer);
                //chartView.repaint();

                //layout.addView(chartView, new LayoutParams(960,LayoutParams.FILL_PARENT));

            }

            chartView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  SeriesSelection seriesSelection = chartView.getCurrentSeriesAndPoint();
                  double[] xy = chartView.toRealPoint(0);

                  if (seriesSelection == null) 
                  {
                    //Toast.makeText(getActivity(), "No chart element was clicked", Toast.LENGTH_SHORT).show();
                  } else {
                      /*
                    Toast.makeText(
                            getActivity(),
                        "Chart element in series index " + seriesSelection.getSeriesIndex()
                            + " data point index " + seriesSelection.getPointIndex() + " was clicked"
                            + " closest point value X=" + seriesSelection.getXValue() + ", Y=" + seriesSelection.getValue()
                            + " clicked point value X=" + (float) xy[0] + ", Y=" + (float) xy[1], Toast.LENGTH_SHORT).show();*/
                    Long values = (long) seriesSelection.getValue();
                    mapValuesText = jsonListString.get(seriesSelection.getSeriesIndex());
                    int xValue = (int)seriesSelection.getXValue()-1;

                    Toast.makeText(getActivity(), "Total produksi minyak "+mapValuesText.get("Text")+", "+dateStringArray.get(xValue)+" = "
                            +NumberFormat.getNumberInstance(Locale.GERMAN).format(values)
                            +" BBLs", Toast.LENGTH_LONG).show();
                  }
                }
              }); 

            LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.dashboard_chart_layout);
            layout.removeAllViews();
            layout.addView(chartView);

        } catch (JSONException e) 
        {
         e.printStackTrace();
        }
    }//End of doInBackground

}//End of AsyncTask

那是我的代码。这是最初加载时发生的情况。

enter image description here

然后,当我尝试缩小图表时会发生这种情况。

enter image description here

您能帮我了解如何管理x轴标签吗?

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您可以侦听panApplied和zoomApplied事件,并相应地更新自定义文本标签。

// an example of handling the zoom events on the chart
mChartView.addZoomListener(new ZoomListener() {
  public void zoomApplied(ZoomEvent e) {
    String type = "out";
    if (e.isZoomIn()) {
      type = "in";
    }
    Log.i("Zoom", "Zoom " + type + " rate " + e.getZoomRate());
  }

  public void zoomReset() {
    Log.i("Zoom", "Reset");
  }
}, true, true);

// an example of handling the pan events on the chart
mChartView.addPanListener(new PanListener() {
  public void panApplied() {
    Log.i("Pan", "New X range=[" + mRenderer.getXAxisMin() + ", " + mRenderer.getXAxisMax() + "], Y range=[" + mRenderer.getYAxisMax() + ", " + mRenderer.getYAxisMax() + "]");
  }
});