//导入我们所使用的依赖
//rxjava
compile 'io.reactivex::x.y.z' compile 'io.reactivex:rxandroid:1.0.1//创建接口//retrofit2
compile 'com.squareup.retrofit2:retrofit:2.0.2'compile 'com.squareup.retrofit2:converter-gson:2.0.2'compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'//recyclerview
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'compile 'com.github.bumptech.glide:glide:3.7.0'
public interface AipServer {
@GET("nba/?key=71e58b5b2f930eaf1f937407acde08fe&num=10")
Observable<Bean<List<NewslistBean>>> getCall();
}
//MainActivity
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList<DataBean> list=new ArrayList<>();
private AipServer server;
private Adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rlv);
LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(manager);
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl("http://api.tianapi.com/")
.build();
server = retrofit.create(AipServer.class);
initData();
adapter = new Adapter(this, list);
recyclerView.setAdapter(adapter);
}
private void initData() {
Observable<Bean<List<NewslistBean>>> call = server.getCall();
call.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Bean<List<NewslistBean>>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Bean<List<NewslistBean>> listBean) {
List<NewslistBean> been = listBean.getNewslist();
for (int i = 0; i < been.size(); i++) {
list.add(new DataBean(been.get(i).getPicUrl(),been.get(i).getTitle()));
}
adapter.notifyDataSetChanged();
}
});
}
}
//适配器
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder > {
private Context context;
private ArrayList<DataBean> list;
public Adapter(Context context, ArrayList<DataBean> list) {
this.context=context;
this.list=list;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=View.inflate(context,R.layout.item,null);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Glide.with(context).load(list.get(position).getImg()).into(holder.imageView);
holder.textView.setText(list.get(position).getName());
}
@Override
public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private final ImageView imageView;
private final TextView textView;
public ViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.textView);
}
}
}
//备注:布局文件以及bean类根据自己所需要添加