2017-01-03 58 views
0

我正在使用MPAndroidChart创建4个图。我是一名初学者,不确定如何在不重复代码的情况下创建我的图。Android java,重复代码

实施例图2

mChart2 = (LineChart)findViewById(R.id.resultGraph2); 
mChart2.setOnChartValueSelectedListener(this); 
mChart2.getDescription().setEnabled(false); 
mChart2.setTouchEnabled(true); 
mChart2.setDragDecelerationFrictionCoef(0.9f); 
mChart2.setDragEnabled(true); 
mChart2.setScaleEnabled(true); 
mChart2.setDrawGridBackground(true); 
mChart2.setHighlightPerDragEnabled(true); 
mChart2.setPinchZoom(true); 
mChart2.setBackgroundColor(Color.WHITE); 
setData2(); 
mChart2.animateX(2500); 
mChart2.getLegend().setEnabled(false); 
mChart2.setExtraLeftOffset(5); 
mChart2.setExtraBottomOffset(10); 

实施例图4

mChart4 = (LineChart)findViewById(R.id.resultGraph4); 
mChart4.setOnChartValueSelectedListener(this); 
mChart4.getDescription().setEnabled(false); 
mChart4.setTouchEnabled(true); 
mChart4.setDragDecelerationFrictionCoef(0.9f); 
mChart4.setDragEnabled(true); 
mChart4.setScaleEnabled(true); 
mChart4.setDrawGridBackground(true); 
mChart4.setHighlightPerDragEnabled(true); 
mChart4.setPinchZoom(true); 
mChart4.setBackgroundColor(Color.WHITE); 
setData4(); 
mChart4.animateX(2500); 
mChart4.getLegend().setEnabled(false); 
mChart4.setExtraLeftOffset(5); 
mChart4.setExtraBottomOffset(10); 

它们都具有相同的设置。 有没有更好的写作方式,无需复制代码?

+5

你听说过一个功能的? –

+0

@JonathonReinhart用户新手:p –

回答

5

例如:

mChart2 = (LineChart)findViewById(R.id.resultGraph2); 
mChart4 = (LineChart)findViewById(R.id.resultGraph4); 
applySettings(mChart2); 
applySettings(mChart4); 

//... 

void applySettings(LineChart chart) 
{ 
    chart.setTouchEnabled(true); 
    chart.setScaleEnabled(true); 
    // etc... 
} 
+0

谢谢,这对我有帮助。 –