Android java,重复代码

Cha*_*eld 0 java android mpandroidchart

我正在使用MPAndroidChart创建4个图表.我是初学者,不知道如何创建我的图形而不重复代码.

示例图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);
Run Code Online (Sandbox Code Playgroud)

示例图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);
Run Code Online (Sandbox Code Playgroud)

它们都具有相同的设置.是否有更好的编写方式,无需复制代码?

Mic*_*ael 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...
} 
Run Code Online (Sandbox Code Playgroud)