RecyclerView+Picasso的使用,把网络图片放在RecyclerView里面
程序员文章站
2024-03-08 20:13:16
...
1.申请网络权限
<!-- 获取网络权限 -->
<uses-permission android:name="android.permission.INTERNET" />
2.添加3个依赖
implementation 'com.android.support:recyclerview-v7:26.1.0'
implementation 'com.squareup.okhttp3:okhttp:4.2.0'
implementation 'com.squareup.picasso:picasso:2.3.2'
3.在layout下面新建一个item.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:background="@android:color/darker_gray"
android:orientation="vertical"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/id_book_image"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_gravity="center_horizontal" />
<TextView
android:id="@+id/id_book_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
/>
</LinearLayout>
4.创建一个java实体类,并设置get方法.
package com.example.a86156.liestview11;
import android.graphics.Bitmap;
import android.widget.ImageView;
public class Book {
private String name; //图片描述
private String url; //网络图片路径
public Book(String name, String url) {
this.name = name;
this.url = url;
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
}
5.创建一个Adapter类
package com.example.a86156.liestview11;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class BookAdapter extends RecyclerView.Adapter<BookAdapter.ViewHolder> {
private List<Book> mBookList;
private Context mContext;
static class ViewHolder extends RecyclerView.ViewHolder{
ImageView bookImage;
TextView bookName;
public ViewHolder(View view){
super(view);
bookImage=view.findViewById(R.id.id_book_image);
bookName=view.findViewById(R.id.id_book_name);
}
}
public BookAdapter(Context context,List<Book> bookList){
mContext = context;
mBookList=bookList;
}
@Override
public BookAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.book_item,parent,false);
RecyclerView.ViewHolder holder=new ViewHolder(view);
return (ViewHolder) holder;
}
@Override
public void onBindViewHolder(BookAdapter.ViewHolder holder, int position) {
Book book=mBookList.get(position);
Picasso.with(mContext).load(mBookList.get(position).getUrl()).resize(200,200).into(holder.bookImage);
holder.bookName.setText(book.getName());
}
@Override
public int getItemCount() {
return mBookList.size();
}
}
6.activity_main.xml布局页面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/id_recycler_view"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="150dp">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
7.MainActivity.java
package com.example.a86156.liestview11;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private List<Book> bookList = new ArrayList<>();
private List<String> listName = new ArrayList<>();
private List<String> listPic = new ArrayList<>();
Button btn;
ImageView imageView;
Handler handler;
Handler handler2;
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
recyclerView = findViewById(R.id.id_recycler_view);
imageView = findViewById(R.id.imgh);
//定时刷新图片,每隔3秒钟刷新一次图片
handler2 = new Handler();
handler2.postDelayed(new Runnable() {
@Override
public void run() {
handler2.postDelayed(this, 3000);
//发送网络请求
sendRequestWithokHttp();
}
}, 2000);
//异步处理,对UI操作
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
init();
}
};
}
private void init() {
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
//设置为横向滑动
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutManager);
BookAdapter adapter = new BookAdapter(MainActivity.this,bookList);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
//发送请求方式1:向云服务器发送请求,返回图片和图片描述
private void sendRequestWithokHttp() {
//开启线程发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
try {
//创建一个OkHttpClient对象
OkHttpClient client = new OkHttpClient();
//创建一个Request用来发送请求
Request request = new Request.Builder()
//请求的目标地址
.url("http://pic.sogou.com/pics/recompic/detail.jsp?")
.build();
//调用okHttpClient的newCall方法创建?Call对象,
//并调用它的execute方法发送请求并获取服务器返回的数据
Response response = client.newCall(request).execute();
String responseData = response.body().string();
//调用该方法解析从服务器返回的XML数据
parseJSONobject1(responseData);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
//发送请求方式2:向云服务器发送请求,返回图片和图片描述
private void sendRequestWithHttpURLConnection() {
//开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://pic.sogou.com/pics/recompic/detail.jsp?");
connection = (HttpURLConnection) url.openConnection();
//设置请求方式
connection.setRequestMethod("GET");
//设置超时时间
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
//下面对获取到的输入流进行读取
BufferedReader bufr = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line = null;
while ((line = bufr.readLine()) != null) {
response.append(line);
}
response.toString();
//解析Json数据
parseJSONobject1(response.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
//解析从服务器获取的json数据
private void parseJSONobject1(String jsonData) {
try {
bookList.clear();
listName.clear();
listPic.clear();
JSONObject jsonObject = new JSONObject(jsonData);
JSONArray jr = new JSONArray(jsonObject.getString("table"));
for (int i = 0; i < jr.length(); i++) {
JSONObject object = new JSONObject(jr.get(i).toString());
listName.add(object.getString("fworkerName"));
listPic.add(object.getString("fpic"));
}
Log.d("头像集合52156", listPic + "");
for (int i = 0; i <listName.size() ; i++) {
Book book = new Book(listName.get(i),listPic.get(i));
bookList.add(book);
}
//不能在子线程中做UI操作,需要异步处理
Message message = new Message();
handler.sendMessage(message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}