Retrofit+rxjava
利用retrofit/rxjava2做一个简单的网络请求、效果是一个轮播图。(轮播图使用的是Banner插件,网址:https://github.com/youth5201314/banner)
建个接口
public interface ApiService {
//以get为例
@GET("/api/v1.0/News/ScrollPic")
Observable <BannerBean>getBanners(@Query("AppKey")String appky,@Query("Timestamp")String timestamp,@Query("Sign")String sign);
}
//简单的对glide进行封装
public class GlideImageLoader extends ImageLoader {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
if(context!=null) {
Glide.with(context).load(path).into(imageView);
}
}
}
//布局文件
<Linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.youth.banner.Banner
android:id="@+id/t1"
android:layout_width="match_parent"
android:layout_height="160dp"
android:text="Hello World!"
/>
</LinearLayout>
//mainActivity
public class MainActivity extends AppCompatActivity {
public static finalStringBASEURL="此处填写网址";
private Banner t;
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t= ((Banner) findViewById(R.id.t1));
Retrofit retrofit=newRetrofit.Builder()
.baseUrl(BASEURL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
ApiService apiService=retrofit.create(ApiService.class);
//此处填写自己的参数
apiService.getBanners("androidkey",“ ”)
//将其切换到主线程
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(newObserver() {
private ArrayList strings;
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull BannerBean bannerBean) {
strings=new ArrayList<>();
for(int i=0;i<bannerBean.getData().size();i++){
strings.add(bannerBean.getData().get(i).getPicurl());
}
t.setImages(strings).setImageLoader(new GlideImageLoader()).start();
}
@Override
public void onError(@NonNull Throwable e){ }
@Override
public void onComplete() {}
});
}