在写Android项目的过程中,我们的项目中很多的内容都是通过RecyclerView列表来实现,今天给大家带来一个超简单的RecyclerView+OKhttp实现一个网络请求的列表,废话不多说,直接上代码
首先第一步就是在我们的gradle中添加依赖
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation "com.github.bumptech.glide:glide:4.6.1" // glide依赖:加载网络图片
//recyclerview
implementation 'com.android.support:recyclerview-v7:27.1.1'
// okhttp
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
//Gson
implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.7'
}
第二步:绘制我们的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:focusableInTouchMode="false"
android:scrollbars="vertical" />
</LinearLayout>
第三步:通过id来找到控件
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//recyclerview列表
initRecycler();
//okhttp网络请求
initOKhttp();
}
private void initRecycler() {
recyclerview = findViewById(R.id.recyclerview);
//设置固定大小
recyclerview.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
recyclerview.setLayoutManager(mLayoutManager);
adapterDelegate = new CompanyAdapterDelegate(this, companies);
recyclerview.setAdapter(adapterDelegate);
recyclerview.setNestedScrollingEnabled(false);
}
private void initOKhttp() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.wanandroid.com/article/list/1/json")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("TAG", "onFailure: " + e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
info json = new Gson().fromJson(string, info.class);
List<info.DataDTO.DatasDTO> datas = json.getData().getDatas();
companies.addAll(datas);
runOnUiThread(() ->
adapterDelegate.notifyDataSetChanged()
);
Log.e("111111", "onResponse: "+string);
}
});
}
第四步:创建适配器
package com.example.myapplication.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapplication.Bean.info;
import com.example.myapplication.R;
import java.util.ArrayList;
public class CompanyAdapterDelegate extends RecyclerView.Adapter<CompanyAdapterDelegate.ViewHolder> {
private LayoutInflater mInflater;
private String[] mTitles=null;
private ArrayList<info.DataDTO.DatasDTO> list;
public CompanyAdapterDelegate(Context context,ArrayList<info.DataDTO.DatasDTO> list){
this.mInflater=LayoutInflater.from(context);
this.list=list;
// for (int i=0;i<20;i++){
// int index=i+1;
// mTitles[i]="item"+index;
// }
}
/**
* item显示类型
* @param parent
* @param viewType
* @return
*/
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=mInflater.inflate(R.layout.item,parent,false);
//view.setBackgroundColor(Color.RED);
ViewHolder viewHolder=new ViewHolder(view);
return viewHolder;
}
/**
* 数据的绑定显示
* @param holder
* @param position
*/
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.item_tv1.setText(list.get(position).getLink());
holder.item_tv2.setText(list.get(position).getNiceShareDate());
holder.item_tv3.setText(list.get(position).getChapterName());
}
@Override
public int getItemCount() {
return list.size();
}
//自定义的ViewHolder,持有每个Item的的所有界面元素
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView item_tv1;
public TextView item_tv2;
public TextView item_tv3;
public ViewHolder(View view){
super(view);
item_tv1 = (TextView)view.findViewById(R.id.text1);
item_tv2 = (TextView)view.findViewById(R.id.text2);
item_tv3 = (TextView)view.findViewById(R.id.text3);
}
}
}
第五步:创建适配器中的xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text1"
android:layout_width="90dp"
android:layout_height="90dp"
android:textColor="#ff00"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/text2"
android:layout_width="90dp"
android:layout_height="90dp"
android:textColor="#CDDC39"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/text3"
android:layout_width="90dp"
android:layout_height="90dp"
android:textColor="#009688"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
最后在我们的清单文件中添加权限
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:allowClearUserData="true"
android:configChanges="keyboardHidden|orientation|screenSize"
android:hardwareAccelerated="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:screenOrientation="portrait"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication"
android:vmSafeMode="true">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
一个简单的RecyclerView+Okhttp的网络请求列表的完成了