实现步骤:
- 阅读API接口使用文档
- 使用okhttp 获取网络数据
- 使用 gson将json数据转为数据实体类
- 安装GsonFormatPlus插件
- 使用glide加载网络图片
- //数据解析
- implementation 'com.google.code.gson:gson:2.8.9'
- //图片加载
- implementation 'com.github.bumptech.glide:glide:4.16.0'
- //网络请求
- implementation 'com.squareup.okhttp3:okhttp:4.11.0'
复制代码
- AndroidManifest.xml 加入网络权限和 application节点下设置
- <uses-permission android:name="android.permission.INTERNET" />
复制代码 注意事项:在手机高版本中,需要在application节点下设置 android:networkSecurityConfig=“@xml/network_security_config”
network_security_config.xml文件如下
- <?xml version="1.0" encoding="utf-8"?>
- <network-security-config xmlns:android="http://schemas.android.com/apk/res/android">
- <base-config cleartextTrafficPermitted="true" />
- </network-security-config>
复制代码
- <?xml version="1.0" encoding="utf-8"?>
- <androidx.appcompat.widget.LinearLayoutCompat 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:orientation="vertical"
- android:layout_height="match_parent"
- tools:context=".NewsActivity">
- <androidx.appcompat.widget.Toolbar
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:background="@color/teal_200"
- app:titleTextColor="@color/white"
- app:title="新闻列表"/>
- <androidx.recyclerview.widget.RecyclerView
- android:id="@+id/recyclerView"
- android:layout_width="match_parent"
- tools:listitem="@layout/new_item"
- app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
- android:layout_height="wrap_content"/>
- </androidx.appcompat.widget.LinearLayoutCompat>
复制代码
- public class NewsListAdapter extends RecyclerView.Adapter<NewsListAdapter.MyHolder> {
- private List<NewsInfo.ResultBean.DataBean> mDataBeanList = new ArrayList<>();
- private Context mContext;
- public NewsListAdapter(Context context) {
- this.mContext = context;
- }
- /**
- * 为adapter 设置数据源
- */
- public void setListData(List<NewsInfo.ResultBean.DataBean> list) {
- this.mDataBeanList = list;
- //一定要调用
- notifyDataSetChanged();
- }
- @NonNull
- @Override
- public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
- //加载布局文件
- View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.new_item, null);
- return new MyHolder(view);
- }
- @Override
- public void onBindViewHolder(@NonNull MyHolder holder, int position) {
- NewsInfo.ResultBean.DataBean dataBean = mDataBeanList.get(position);
- //设置数据
- holder.author_name.setText(dataBean.getAuthor_name());
- holder.title.setText(dataBean.getTitle());
- holder.date.setText(dataBean.getDate());
- //加载图片
- Glide.with(mContext).load(dataBean.getThumbnail_pic_s()).error(R.mipmap.img_error).into(holder.thumbnail_pic_s);
- }
- @Override
- public int getItemCount() {
- return mDataBeanList.size();
- }
- static class MyHolder extends RecyclerView.ViewHolder {
- ImageView thumbnail_pic_s;
- TextView title;
- TextView author_name;
- TextView date;
- public MyHolder(@NonNull View itemView) {
- super(itemView);
- thumbnail_pic_s = itemView.findViewById(R.id.thumbnail_pic_s);
- title = itemView.findViewById(R.id.title);
- author_name = itemView.findViewById(R.id.author_name);
- date = itemView.findViewById(R.id.date);
- }
- }
- }
复制代码
- <?xml version="1.0" encoding="utf-8"?>
- <androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
- <androidx.appcompat.widget.LinearLayoutCompat
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_margin="10dp">
- <ImageView
- android:id="@+id/thumbnail_pic_s"
- android:layout_width="90dp"
- android:layout_height="100dp"
- android:scaleType="centerCrop"
- android:src="@mipmap/ic_launcher" />
- <androidx.appcompat.widget.LinearLayoutCompat
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_marginLeft="10dp"
- android:orientation="vertical">
- <TextView
- android:id="@+id/title"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginTop="10dp"
- android:text="静音车厢”绝非一劳永逸,考验仍在"
- android:textColor="#333"
- android:textSize="16sp"
- android:singleLine="true"
- android:textStyle="bold" />
- <TextView
- android:id="@+id/author_name"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginTop="10dp"
- android:text="每日看点快看" />
- <TextView
- android:id="@+id/date"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginTop="10dp"
- android:text="2023-10-17 08:34:00" />
- </androidx.appcompat.widget.LinearLayoutCompat>
- </androidx.appcompat.widget.LinearLayoutCompat>
- </androidx.appcompat.widget.LinearLayoutCompat>
复制代码
- public class NewsActivity extends AppCompatActivity {
- private static String URL = "http://v.juhe.cn/toutiao/index?key=b6527106fa4e66a226b5b923d2a8b711&type=yule";
- private RecyclerView mRecyclerView;
- private NewsListAdapter mNewsListAdapter;
- private Handler mHandler = new Handler(Looper.getMainLooper()) {
- @Override
- public void handleMessage(@NonNull Message msg) {
- if (msg.what == 100) {
- String data = (String) msg.obj;
- NewsInfo newsInfo = new Gson().fromJson(data, NewsInfo.class);
- //刷新适配器
- if (null!=mNewsListAdapter){
- mNewsListAdapter.setListData(newsInfo.getResult().getData());
- }
- }
- }
- };
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_news);
- //初始化控件
- mRecyclerView = findViewById(R.id.recyclerView);
- //初始化适配器
- mNewsListAdapter = new NewsListAdapter(NewsActivity.this);
- //绑定适配器
- mRecyclerView.setAdapter(mNewsListAdapter);
- getHttpData();
- }
- private void getHttpData() {
- //创建OkHttpClient对象
- OkHttpClient okHttpClient = new OkHttpClient();
- //构构造Request对象
- Request request = new Request.Builder()
- .url(URL)
- .get()
- .build();
- //通过OkHttpClient和Request对象来构建Call对象
- Call call = okHttpClient.newCall(request);
- //通过Call对象的enqueue(Callback)方法来执行异步请求
- call.enqueue(new Callback() {
- @Override
- public void onFailure(@NonNull Call call, @NonNull IOException e) {
- Log.d("-------------", "onFailure: "+e.toString());
- }
- @Override
- public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
- // Log.d("--------------", "onResponse: " + response.body().string());
- String data = response.body().string();
- Message message = new Message();
- //指定一个标识符
- message.what = 100;
- message.obj = data;
- mHandler.sendMessage(message);
- }
- });
- }
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |