Android项目实战 | 从零开始写app实现服务端智慧服务页面数据的解析

Posted 李猫er

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android项目实战 | 从零开始写app实现服务端智慧服务页面数据的解析相关的知识,希望对你有一定的参考价值。

本系列即将完结,整理一下每个小章节,希望入门的学习者能看懂,并且帮助到你,其他勿cue,这只是一个简单的app小demo~

本篇效果

在这里插入图片描述
总体,实现服务端服务端功能的数据解析,处理RecyclerView中item子项的点击事件并实现跳转到对应的服务页面,接来下看代码吧~

文章导航

一、【Android项目实战 | 从零开始写app(一)】 创建项目

二、【Android项目实战 | 从零开始写app(二)】实现闪屏页,启动app

三、【Android项目实战 | 从零开始写app(三)】实现引导页,进入登录or主页面

四、【Android项目实战 | 从零开始写app(四)】Okhttp+Gson实现服务端登录验证功能

五、【Android项目实战 | 从零开始写app(五)】okhttp+gson实现服务端注册功能

六、【Android项目实战 | 从零开始写app(六)】用TabLayout+ViewPager搭建App 框架主页面底部导航栏

七、【Android项目实战 | 从零开始写app(七)】优化主页导航栏,禁用主页页面滑动切换效果

八、【Android项目实战 | 从零开始写app(八)】实现app首页广告轮播图切换和搜索跳转

九、【Android项目实战 | 从零开始写app(九)】Tablayout+ViewPager实现页面分类顶部标题页面联动切换

十、【Android项目实战 | 从零开始写app(十)】Okhttp+glide+json+ListView实现新闻模块数据的填充显示

十一、【Android项目实战 | 从零开始写app(十一)】实现app首页智慧服务页面服务分类数据的解析及点击跳转

十二、【Android项目实战 | 从零开始写app(十二)】实现app首页智慧服务&热门推荐&热门主题、新闻

十三、【Android项目实战 | 从零开始写app(十三)】实现用户中心模块清除token退出登录&信息修改等功能

十四、【Android项目实战 | 从零开始写app(十四)】实现图片发布模块 | 必知必会之调用系统相机拍照、相册

十五、【Android项目实战 | 从零开始写app(教程汇总)】Android 项目实战系列汇总、源代码


功能实现

ServiceActivity

package com.example.smartcity.activity;

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

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.smartcity.R;
import com.example.smartcity.adapter.RecycleServiceAdapter;
import com.example.smartcity.bean.ServiceBean;
import com.example.smartcity.utils.APIConfig;
import com.google.gson.Gson;

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

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ServiceActivity extends AppCompatActivity {

    private RecyclerView service_recyclerview;
    private RecycleServiceAdapter adapter;
    private List<ServiceBean.RowsBean> rowsBeanList;


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==0) {
                ServiceBean serviceBean = (ServiceBean) msg.obj;
                rowsBeanList = serviceBean.getRows();
                // 实例化adapter
                adapter= new RecycleServiceAdapter(ServiceActivity.this,rowsBeanList);
                // 设置布局管理器
                service_recyclerview.setLayoutManager(new GridLayoutManager(ServiceActivity.this,5));
                // 设置适配器
                service_recyclerview.setAdapter(adapter);
                // 设置item点击跳转事件 分别到对应的页面,在Intent中可以自己创建跳转的activity
                adapter.setItemClickListener(new RecycleServiceAdapter.MyItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        String url = APIConfig.BASE_URL+"/"+rowsBeanList.get(position).getLink();
                        Intent intent = null;
                        if (position==0){
                            intent = new Intent(ServiceActivity.this, CityStateActivity.class);
                        } else if (position==1) {
                            intent = new Intent(ServiceActivity.this, BusActivity.class);
                        } else if (position==2) {
                            intent = new Intent(ServiceActivity.this, ApponitmentActivity.class);
                        } else if (position==3) {
                            intent = new Intent(ServiceActivity.this, LivingPayActivity.class);
                        } else if (position==4) {
                            intent = new Intent(ServiceActivity.this, WeiZhangActivity.class);
                        } else if (position==5) {
                            intent = new Intent(ServiceActivity.this, ParkActivity.class);
                        }
                        Bundle bundle = new Bundle();
                        bundle.putString("title",rowsBeanList.get(position).getServiceName());
                        bundle.putString("url",url);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
        service_recyclerview = findViewById(R.id.service_recyclerview);
        getServiceData();
    }

    // 请求全部服务
    private void getServiceData() {
        // 创建OkHttpClient对象
        OkHttpClient client = new OkHttpClient();
        // 创建 Request对象
        Request request = new Request.Builder()
                .url(APIConfig.BASE_URL+"/service/service/list")
                .build();
        try {
            // 回调
            Call call = client.newCall(request);
            // 异步请求
            call.enqueue(new okhttp3.Callback() {
                @Override
                // 请求失败
                public void onFailure(Call call, IOException e) {
                    Log.i("onFailure",e.getMessage());
                }
                // 响应成功
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        final String result = response.body().string();
                        // runOnUiThread()用于更新UI
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Gson gson = new Gson();
                                ServiceBean serviceBean = gson.fromJson(result,ServiceBean.class);
                                Message msg = new Message();
                                msg.what=0;
                                msg.obj=serviceBean;
                                handler.sendMessage(msg);
                            }
                        });
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

activity_service.xml

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".activity.ServiceActivity">

    <!--服务-->
    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#B5D6F1"
        android:layout_margin="10dp"
        android:padding="10dp"
        android:id="@+id/service_recyclerview"/>

</LinearLayout>

service_item

设置每项item布局
在这里插入图片描述

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_weight="1"
    android:layout_gravity="center"
    android:layout_marginTop="20dp"
    android:layout_height="wrap_content">
    <ImageView
        android:background="@drawable/category_shape"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center"
        android:id="@+id/service_img"
        android:src="@mipmap/ic_launcher"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/service_name"
        android:textSize="20sp"
        android:textColor="#131313"
        android:layout_gravity="center"
        android:text="智慧出行"
        />
</LinearLayout>

RecycleServiceAdapter

package com.example.smartcity.adapter;

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 com.example.smartcity.R;
import com.example.smartcity.bean.ServiceBean;
import com.example.smartcity.utils.APIConfig;

import java.util.List;

/**
 * @ProjectName: smartcity
 * @Package: com.example.smartcity.adapter
 * @ClassName: RecycleServiceAdapter
 * @Description: RecyclerView 全部服务适配器
 * @Author: liyingxia
 * @CreateDate: 2021/3/31 21:28
 */
public class RecycleServiceAdapter extends RecyclerView.Adapter<RecycleServiceAdapter.MyViewHolder> {
    private LayoutInflater layoutInflater;
    private List<ServiceBean.RowsBean> rowsBeans;
    private Context context;
    private MyItemClickListener mItemClickListener;

    /**
     * 构造方法 传入参数
     * @param context
     * @param rowsBeans
     */
    public RecycleServiceAdapter(Context context,List<ServiceBean.RowsBean> rowsBeans) {
        this.rowsBeans = rowsBeans;
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 创建ViewHolder, 返回每一项的布局
        View view = layoutInflater.inflate(R.layout.service_item,parent,false);
        MyViewHolder myViewHolder = new MyViewHolder(view,mItemClickListener);
        return myViewHolder;
    }

    // 将数据与控件绑定
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.service_name.setText(rowsBeans.get(position).getServiceName());
        String url = APIConfig.BASE_URL + rowsBeans.get(position).getImgUrl();
        Glide.with(context).load(url).into(holder.service_img);
    }

    // 返回Item总条数
    @Override
    public int getItemCount() {
       // return 10;
        return rowsBeans.size();
    }

    // 内部类,绑定控件
    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView service_name;
        private ImageView service_img;
        private MyItemClickListener myListener;

        public MyViewHolder(@NonNull View view,MyItemClickListener myItemClickListener) {
            super(view);
            this.myListener = myItemClickListener;
            itemView.setOnClickListener(this);
            service_img = view.findViewById(R.id.service_img);
            service_name = view.findViewById(R.id.service_name);
        }

        @Override
        public void onClick(View view) {
            if (myListener!=null) {
                myListener.onItemClick(view,getPosition());
            }
        }
    }

    //创建一个回调接口
    public interface MyItemClickListener {
        void onItemClick(View view,int position);
    }
    //在activity中adapter中调用此方法,将点击事件监听传递过去,并赋值给全局监听
    public void setItemClickListener(MyItemClickListener myItemClickListener){
        this.mItemClickListener = myItemClickListenerAndroid项目实战 | 从零开始写app(十三)实现用户中心模块清除token退出登录&信息修改等功能

Android项目实战 | 从零开始写app(14)实现图片发布模块 | 必知必会之调用系统相机拍照相册一一解决android7 打开相机闪退奔溃问题

从零开始怎么写android native service?

从零开始怎么写android native service?

《Android Studio开发实战 从零基础到App上线(第3版)》出版后记

《Android Studio开发实战 从零基础到App上线(第3版)》出版后记