我对此有点迷失MPAndroid chart library 。
我开始了初学者示例here ,它建议使用 getValueX() 和 getValueY() 方法创建一个对象数组/列表,然后将其添加为条目,如下所示:
List<Entry> entries = new ArrayList<Entry>(); // entry list
for(ValueAndDateObject data : valueAndDateArrayList){
// valueAndDateArrayList is the list of my own data
//(objects with a String X-value, and a double Y-value)
entries.add(new Entry(data.getValueX(), data.getValueY())); //error here
}
那里有一个错误,因为 Entry 只接受 (float x, float y)。显然我可以将 double 型转换为 float ,但我需要 x 轴的日期不是 float 。所以我做了一些更多的搜索,发现了很多关于它的 Github 问题,但那里的解决方案我似乎无法理解。大多数人都指向类似 this in the docs 的东西。我遇到的问题是我不明白这如何应用于 Entry(float x, float y) 问题。我找不到文档/解决方案说适用于 Entry() 的时间/地点。
因此,当我查看有关创建格式化程序然后设置它的示例时,我不明白entries.add(new Entry()) 的内容来自何处。该技术是否会取代它?我是否以某种方式传递它?
作为引用,这是我的完整方法,是根据前面提到的初学者示例设计的。
public void updateUI(final ArrayList<ValueAndDateObject> valueAndDateArrayList){
List<Entry> entries = new ArrayList<Entry>();
for(ValueAndDateObject data : valueAndDateArrayList){
/** for the sake of the example, let's say there's only one
* ValueAndDataObject in the list and getValueX() returns "02-27-2016"
* and getValueY() returns 12,345.0
*/
entries.add(new Entry(data.getValueX(), data.getValueY())); //error obviously
}
// would I add the formatter somewhere in here? And what would I "add" it to?
LineDataSet dataSet = new LineDataSet(entries, "Label");
dataSet.setColor(Color.YELLOW);
dataSet.setValueTextColor(Color.BLACK);
LineData lineData = new LineData(dataSet);
lineChart.setData(lineData);
lineChart.invalidate();
}
据我所知,我必须创建自己的格式化程序类,我将根据格式化程序文档链接中的 string[] 示例对其进行建模。我的挂断是在“设置格式化程序”部分。只是不确定这将如何改变/与 Entry(float x, float y) 问题相互作用。
最佳答案
您只需在创建 Entry
对象时将 Date
视为时间戳,例如:
entries.add(new Entry(new Long(data.getDate().getTime()).floatValue(), new Double(data.getValueY()).floatValue()));
在上面,我们假设 data.getDate()
返回一个 java.util.Date
并且 data.getValueY()
返回一个double
。
然后,您在 IAxisValueFormatter
中所需要做的就是将时间戳表示形式转换回 Date
,然后转换为人类可读的内容,如下所示:
public class DateValueFormatter implements IAxisValueFormatter {
@Override
public String getFormattedValue(float value, AxisBase axis) {
// Simple version. You should use a DateFormatter to specify how you want to textually represent your date.
return new Date(new Float(value).longValue()).toString();
}
// ...
}
更新:
设置值格式化程序:
XAxis xAxis = chart.getXAxis();
xAxis.setValueFormatter(new DateValueFormatter());
更新:
用户“Yasir-Ghunaim”在 this thread on github 中提供了非常好的分步指南作为回复。 。
关于java - MPAndroidChart - 如何最好地将 X 轴值设置为字符串/日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42909979/