其他分享
首页 > 其他分享> > 具有自定义水平标签的Android-GraphView无法正常显示

具有自定义水平标签的Android-GraphView无法正常显示

作者:互联网

我试图制作图表,其中x轴包含日期作为字符串.所以我使用customLabelFormatter它给了我一年约365个日期的所有日期.

现在,问题是x轴显示所有日期,但在非常共轭的空间,所以它看起来像一条直线.

这是我的代码:

public class TestActivity extends Activity {

private RelativeLayout grapahcontainer;

private String[] dates;
private Random rand;
private SimpleDateFormat dateFormat = new SimpleDateFormat("d/M");

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    grapahcontainer = (RelativeLayout) findViewById(R.id.graph);
    rand = new Random();
    dates = new String[366];
    getDates();

    int size = dates.length;

    GraphViewData[] data = new GraphViewData[size];
    for (int i = 0; i < size; i++) {
        data[i] = new GraphViewData(i, rand.nextInt(800)); 
    }


    LineGraphView graphView = new LineGraphView(this, "GraphViewDemo");
    graphView.setCustomLabelFormatter(new CustomLabelFormatter() {

        @Override
        public String formatLabel(double value, boolean isValueX) {
            // TODO Auto-generated method stub
            if (isValueX) {
                return dateFormat.format(new Date());
            }
            return null;
        }
    });

    graphView.setDrawDataPoints(true);
    graphView.setDataPointsRadius(5f);

    // add data
    graphView.addSeries(new GraphViewSeries(data));


    graphView.getGraphViewStyle().setGridColor(Color.TRANSPARENT);
    graphView.getGraphViewStyle().setHorizontalLabelsColor(Color.GRAY);
    graphView.getGraphViewStyle().setVerticalLabelsColor(Color.GRAY);
    graphView.getGraphViewStyle().setTextSize(10);

    graphView.getGraphViewStyle().setVerticalLabelsWidth(30);

    graphView.setHorizontalLabels(dates);
    graphView.setVerticalLabels(getResources().getStringArray(
            R.array.verticalLbls));


    // set view port, start=0, size=8
    graphView.setViewPort(0, 8);
    graphView.setScrollable(true);

    RelativeLayout.LayoutParams graphViewpParams = new RelativeLayout.LayoutParams(
            300, 500);
    graphView.setLayoutParams(graphViewpParams);
    grapahcontainer.addView(graphView);
}

private void getDates() {

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, 1);
    calendar.add(Calendar.DATE, -365);
    dates[0] = (dateFormat.format(calendar.getTime()));
    for (int i = 0; i < 365; i++) {
        calendar.add(Calendar.DATE, 1);
        String dateStr = dateFormat.format(calendar.getTime());
        // System.out.println("Date : " + dateStr);
        dates[i + 1] = dateStr;
    }
}

}

解决方法:

您可以使用GraphViewStyle的这两种方法设置标签数量:

> setNumHorizontalLabels(int numHorizontalLabels) 
> setNumVerticalLabels(int numVerticalLabels)

标签:android,android-graphview
来源: https://codeday.me/bug/20190708/1406726.html