Android RecyclerView+Okhttp的简单使用

通过一个Demo讲解RecyclerView+Okhttp的结合使用

  1. 首先要新建项目

  2. 添加网络权限

    <uses-permission android:name="android.permission.INTERNET" />
    

    Android9.0以上版本需要设置 networkSecurityConfig
    在res新建xml包
    新建一个xml文件 network_security_config.xml
    内容如下:

       <?xml version="1.0" encoding="utf-8"?>
       <network-security-config>
           <base-config cleartextTrafficPermitted="true" />
       </network-security-config>
    
  3. 添加依赖
    implementation ‘androidx.recyclerview:recyclerview:1.2.0-alpha01’
    implementation ‘com.squareup.okhttp3:okhttp:3.12.1’
    implementation ‘com.google.code.gson:gson:2.8.6’
    //下面两个是glide
    implementation ‘com.github.bumptech.glide:glide:4.10.0’
    annotationProcessor ‘com.github.bumptech.glide:compiler:4.10.0’

  4. 封装OKhttp

  5. 布局中添加Recyclerview

  6. 编写item布局

  7. 编写适配器

  8. 设置数据与适配器
    最终效果:最终效果
    API接口大全:
    https://apiopen.top/api.html

布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recy"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>

iitm布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/textTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="标题"
        android:layout_gravity="center"
        android:textSize="20dp"/>
    <ImageView
        android:id="@+id/imgPic"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@mipmap/demo"`在这里插入代码片`
        android:layout_gravity="center"/>
    <TextView
        android:id="@+id/textTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="标题"
        android:layout_gravity="center"
        android:textSize="20dp"/>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#000"/>
</LinearLayout>

http请求:

public class HttpUtils{
    private static OkHttpClient client = new OkHttpClient();
    public static void get(String ip, Callback callback){
        Request request = new Request
                .Builder()
                .url(ip)
                .get()
                .build();
        client.newCall(request).enqueue(callback);
    }
}

适配器:

package cn.njcit.demoapp;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.List;

/**
 * Create by ankele
 * <p>
 * 2020/2/7 - 13:49
 */
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {

    private Context context;
    private List<NewsBean.ResultBean> datas;

    public NewsAdapter(Context context, List<NewsBean.ResultBean> datas) {
        this.context = context;
        this.datas = datas;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_news,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        NewsBean.ResultBean data = datas.get(position);
        holder.textTitle.setText(data.getTitle());
        Glide.with(context).load(data.getImage()).into(holder.imgPic);
        holder.textTime.setText(data.getPasstime());
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        ImageView imgPic;
        TextView textTitle;
        TextView textTime;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            imgPic = (ImageView)itemView.findViewById(R.id.imgPic);
            textTitle = (TextView)itemView.findViewById(R.id.textTitle);
            textTime = (TextView)itemView.findViewById(R.id.textTime);
        }
    }
}

MainActivity:

package cn.njcit.demoapp;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecy;
    private List<NewsBean.ResultBean> datas = new ArrayList<>();
    private NewsBean newsBean;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }

    private void initView() {
        mRecy = (RecyclerView) findViewById(R.id.recy);
    }
    private void initData(){
        HttpUtils.get("https://api.apiopen.top/getWangYiNews?page=1&count=5", new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "访问失败"+e, Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call,final Response response) throws IOException {
                final String string = response.body().string();
                final Gson gson = new Gson();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (response.isSuccessful()){
                            newsBean = gson.fromJson(string,NewsBean.class);
                            if (newsBean.getCode()==200){
                                datas.addAll(newsBean.getResult());
                                handler.sendEmptyMessage(1);
                            }
                        }
                    }
                });
            }
        });
    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    mRecy.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                    mRecy.setAdapter(new NewsAdapter(MainActivity.this,datas));
                    break;
            }
        }
    };
}

目前的正在做的开源项目:

https://github.com/Jetlonglong/AnkeRead

发布了1 篇原创文章 · 获赞 1 · 访问量 56

猜你喜欢

转载自blog.csdn.net/larry_longlong/article/details/104215110
今日推荐