使用Retrofit+Rxjava+MPAndroid來顯示氣溫曲線圖
這里是抓包抓來API接口:http://aider.meizu.com/app/weather/listWeather?cityIds=101020600
先看一下最終的結果:

好吧,下面就正式開始項目吧~
1.導入第三方庫
//okhttp
compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.squareup.okio:okio:1.11.0'
compile
//butterknife
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
//Rxjava
compile 'io.reactivex:rxjava:1.1.3'
compile 'io.reactivex:rxandroid:1.1.0'
//Retrofit
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:converter-scalars:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
//gson
compile files('libs/gson-2.6.2.jar')
//MPAndroid
compile 'com.github.PhilJay:MPAndroidChart:v3.0.1'
2.初始化設置
-
布局文件
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/andro id" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin " android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.skkk.okhttp3stydy.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:text="Demo" android:gravity="center" android:ems="10" android:id="@+id/editText" /> <Button android:text="下載圖片" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/button2" /> <com.github.mikephil.charting.charts.LineChart android:id="@+id/lc_weather_future" android:layout_width="match_parent" android:layout_height="300dp" ></com.github.mikephil.charting.charts.LineChar t> <com.github.mikephil.charting.charts.LineChart android:id="@+id/lc_weather_detail" </LinearLayout> </android.support.v4.widget.NestedScrollView>
很簡單,一個標題,一個按鈕,一個折線圖
-
然后我們設置一個Gson的接收類
...(此處省略)
-
Retrofit的接口文件
public interface WeatherInterface { //http://aider.meizu.com/app/weather/listWeather?cityId s=101010100 @GET("app/weather/listWeather") Observable<WeatherGson> getWeather(@Query("cityIds")String cityIds); }
-
初始化網絡請求
String baseUrl = "http://aider.meizu.com/"; retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.creat e()) .addCallAdapterFactory(RxJavaCallAdapterFactory .create()) .baseUrl(baseUrl) .build(); WeatherInterfaceweatherInterface=retrofit.create(WeatherInt erface.lass)
3.邏輯編寫
-
獲取被監聽者
Observable<WeatherGson> weatherRequest =weatherInterface.getWeather("101020600");
-
網絡請求
weatherRequest.subscribeOn(Schedulers.newThread())
-
數據處理(將獲取到的Gson數據轉化為MPAndroid需求的數據)
這個demo中我們僅僅需要數據中的未來六天日夜間氣溫變化數據就
1.獲取目標數據
//獲取未來天氣 WeatherDetailsInfo weatherDetailsInfo = weatherGson.getValue().get(0).getWeatherDetailsInfo(); List<Weather> weathers =weatherGson.getValue().get(0).getWeathers();
2.轉化為MPAndroid需求值List<Entry>
List<Entry> entryListD = new ArrayList<Entry>(); List<Entry> entryListN = new ArrayList<Entry>(); for (int i = 0; i < weathers.size(); i++) { //將天氣對象轉化為圖標中的數據元 entryListD.add(new Entry(i, Float.valueOf(weathers.get(i).getTempDayC()))); entryListN.add(new Entry(i, Float.valueOf(weathers.get(i).getTempNightC()))); //將星期幾添加到數組中 days[i] = weathers.get(i).getWeek(); }
3.這里還需要設置一下chart中的橫軸坐標格式器
//設置X軸的格式 xFormatter = new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { return days[(int) value]; } };
4.設置折線圖數據并返回
List<LineDataSet> lineDataSetList = new ArrayList<LineDataSet>(); lineDataSetList.add(new LineDataSet(entryListD, getString(R.string.future_weather_day))); lineDataSetList.add(new LineDataSet(entryListN, getString //返回直線圖數據對象 return lineDataSetList;
4.監聽者主線程更新UI
-
接收數據
Observable<WeatherGson> weatherRequest = weatherInterface.getWeather("101020600"); weatherRequest.subscribeOn(Schedulers.newThread()) .subscribeOn(Schedulers.io()) .map(new Func1<WeatherGson, List<LineDataSet>>() { @Override public List<LineDataSet> call(WeatherGson weatherGson) { ... //返回直線圖數據對象 return lineDataSetList; } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<List<LineDataSet>>() { @Override public void onCompleted() { Toast.makeText(MainActivity.this, "完成網絡!", Toast.LENGTH_SHORT).show(); } @Override public void onError(Throwable e) { Toast.makeText(MainActivity.this, "網絡錯誤!", Toast.LENGTH_SHORT).show(); } @Override public void onNext(List<LineDataSet> lineDataSetList) { //顯示圖表 showChart(lineDataSetList); } });
-
更新chart
private void showChart(List<LineDataSet> dataSetList) { //設置日間溫度曲線 dataSetList.get(0).setMode(LineDataSet.Mode.HORIZONTAL_BEZIER); dataSetList.get(0).setColor(ContextCompat.getColor(this,R.color.colorAccent)); dataSetList.get(0).setDrawCircleHole(false); dataSetList.get(0).setDrawCircles(false); //設置晚間溫度曲線 dataSetList.get(1).setMode(LineDataSet.Mode.HORIZONTAL_BEZIER); dataSetList.get(1).setColor(ContextCompat.getColor(this,R.color.colorPrimaryDark)); dataSetList.get(1).setDrawCircleHole(false); dataSetList.get(1).setDrawCircles(false); //設置數據 LineData dayLineData = new LineData(); LineData infoLineData = new LineData(); for (int i = 0; i < dataSetList.size(); i++) { dayLineData.addDataSet(dataSetList.get(i)); } dayLineData.setValueFormatter(vFormatter); dayLineData.setValueTextSize(8f); dayLineData.setValueTextColor(Color.BLACK); //設置X軸 XAxis dayXAxis = mDayLineChart.getXAxis(); dayXAxis.setDrawGridLines(false); dayXAxis.setPosition(XAxis.XAxisPosition.BOTTOM); dayXAxis.setValueFormatter(xFormatter); //設置Y軸right YAxis axisRight = mDayLineChart.getAxisRight(); axisRight.setDrawAxisLine(false); axisRight.setDrawGridLines(false); axisRight.setDrawLabels(false); //設置Y軸left YAxis axisLeft = mDayLineChart.getAxisLeft(); axisLeft.setDrawAxisLine(false); axisLeft.setDrawGridLines(false); axisLeft.setDrawLabels(false); //設置chart Description description = new Description(); description.setText("氣溫預測圖"); description.setTextSize(15f); description.setTextColor(getResources().getColor(R.color.colorPrimaryDark)); mDayLineChart.setDescription(description); mDayLineChart.setData(dayLineData); mDayLineChart.setMarker(mIMarker); mDayLineChart.invalidate();
5.查看源碼
一起進步吧,少年~
點擊這里查看源碼