(仿头条APP项目)4.父类BaseFragment创建,用retrofit和gson获取并解析服务器端数据

文章目录

  • 父类BaseFragment创建,用retrofit和gson获取并解析服务器端数据
    • 效果展示
    • 创建父类BaseFragment解决代码重复问题
    • 用retrofit和gson获取并解析服务器端数据
      • 前期准备
        • 导入依赖
        • 获取网络权限
      • 具体实现
        • 创建Api,retrofit方法与注解实现类
        • 复制服务端数据,利用GsonFormat快速创建Bean类
        • 在首页Fragment编写相应代码

父类BaseFragment创建,用retrofit和gson获取并解析服务器端数据

效果展示

(仿头条APP项目)4.父类BaseFragment创建,用retrofit和gson获取并解析服务器端数据_第1张图片

创建父类BaseFragment解决代码重复问题

在昨天的开发中,利用了判断成员变量View是否为空解决数据丢失问题,ViewGroup的remove来解决重用parent问题。而这是每个Fragment都会产生的问题,每个都有相同的代码处理,这样不好。所以创建了一个所有Fragment界面的父类来解决这个问题
BaseFragment

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class BaseFragment extends Fragment {
    protected View view = null;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //判断view是否为空
        if(view==null) {
            view = getMyView();
        }else {
            //清除当前重用的view的parent
            ViewGroup viewGroup = (ViewGroup) view.getParent();
            if (viewGroup!=null){
                viewGroup.removeView(view)  ;
            }
        }
        return view;
    }
    protected View getMyView() {
        TextView textView= new TextView(getActivity());
        textView.setBackgroundColor(Color.GRAY);
        textView.setText("页面");
        textView.setTextSize(30);
        textView.setGravity(Gravity.CENTER);
        return textView;
    }
}

所有Fragment页面继承BaseFragment 并重写getMyView()方法

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.xzit.fragment.BaseFragment;

public class Page1Fragment extends BaseFragment {
    @Override
    protected View getMyView() {
        TextView textView= new TextView(getActivity());
        textView.setBackgroundColor(Color.GRAY);
        textView.setText("北京");
        textView.setTextSize(60);
        textView.setGravity(Gravity.CENTER);
        return textView;
    }
}

用retrofit和gson获取并解析服务器端数据

前期准备

导入依赖

//配置retrofit
implementation ‘com.squareup.retrofit2:retrofit:2.1.0’
implementation ‘com.squareup.retrofit2:converter-gson:2.1.0’
//gson
implementation ‘com.google.code.gson:gson:2.8.4’
(仿头条APP项目)4.父类BaseFragment创建,用retrofit和gson获取并解析服务器端数据_第2张图片

获取网络权限

(仿头条APP项目)4.父类BaseFragment创建,用retrofit和gson获取并解析服务器端数据_第3张图片

具体实现

创建Api,retrofit方法与注解实现类

(仿头条APP项目)4.父类BaseFragment创建,用retrofit和gson获取并解析服务器端数据_第4张图片

复制服务端数据,利用GsonFormat快速创建Bean类

(仿头条APP项目)4.父类BaseFragment创建,用retrofit和gson获取并解析服务器端数据_第5张图片
(仿头条APP项目)4.父类BaseFragment创建,用retrofit和gson获取并解析服务器端数据_第6张图片

import java.util.List;

public class ResponseDate {

    /**
     * data : [{"id":10007,"title":"北京","type":1,"url":"10007/list_1.json"},{"id":10006,"title":"中国","type":1,"url":"10006/list_1.json"},{"id":10008,"title":"国际","type":1,"url":"10008/list_1.json"},{"id":10010,"title":"体育","type":1,"url":"10010/list_1.json"},{"id":10091,"title":"生活","type":1,"url":"10091/list_1.json"},{"id":10012,"title":"旅游","type":1,"url":"10012/list_1.json"},{"id":10095,"title":"科技","type":1,"url":"10095/list_1.json"},{"id":10009,"title":"军事","type":1,"url":"10009/list_1.json"},{"id":10093,"title":"时尚","type":1,"url":"10093/list_1.json"},{"id":10011,"title":"财经","type":1,"url":"10011/list_1.json"},{"id":10094,"title":"育儿","type":1,"url":"10094/list_1.json"},{"id":10105,"title":"汽车","type":1,"url":"10105/list_1.json"}]
     * retcode : 200
     */

    public int retcode;
    public List<DataBean> data;

    public static class DataBean {
        /**
         * id : 10007
         * title : 北京
         * type : 1
         * url : 10007/list_1.json
         */

        public int id;
        public String title;
        public int type;
        public String url;
    }
}

在首页Fragment编写相应代码

HomeFragment

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.example.administrator.zhjrtt.R;
import com.google.gson.Gson;
import com.xzit.bean.ResponseDate;
import com.xzit.fragment.sub.Page1Fragment;
import com.xzit.fragment.sub.Page2Fragment;
import com.xzit.fragment.sub.Page3Fragment;
import com.xzit.fragment.sub.Page4Fragment;
import com.xzit.fragment.sub.Page5Fragment;
import com.xzit.net.MyApi;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class HomeFragment extends BaseFragment {
    class MyPagerAdapter extends FragmentPagerAdapter{
        //创建集合存放页面
        private List<ResponseDate.DataBean> dates = new ArrayList<>();
        //创建集合存放指示器标题
        private List<Fragment> fragments = new ArrayList<>();
        public MyPagerAdapter(FragmentManager fm,List<ResponseDate.DataBean> list) {
            super(fm);
            //将一个集合中所有的数据加到当前的datas
            dates.addAll(list);
            for (ResponseDate.DataBean item:dates
                 ) {
                fragments.add(new Page1Fragment());
            }
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            //返回指定位置标题内容
            return dates.get(position).title;
        }

        @Override
        public Fragment getItem(int i) {
            //返回页面内容
            return fragments.get(i);
        }

        @Override
        public int getCount() {
            //返回页面数量
            return dates.size();
        }
    }
    MyPagerAdapter myPagerAdapter;
    TabLayout tabLayout;
    ViewPager viewPager;
    @Override
    protected View getMyView() {
        //1.布局viewpager
        //2.加载
        View view = View.inflate(getActivity(),R.layout.fragment_home,null);
         viewPager = view.findViewById(R.id.vp_home);
        //3.定义适配器
        //4.初始化设置适配器
        //5.初始化指示器
         tabLayout = view.findViewById(R.id.tl_home);
        //向服务端获取数据
        getDate();
        return view;
    }

    private void getDate() {
        //1.创建retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.31.114:8080/jrtt/")//会将地址和方法上的注解进行拼接
                .addConverterFactory(GsonConverterFactory.create(new Gson()))//添加一个转换工厂,调用Gson对象,将json数据转换为java对象
                .build();//执行创建
        //2:重点是发请求获取服务的数据
        MyApi myApi = retrofit.create(MyApi.class);
        //3:将json数据处理一下,使用插件gsonformat生成javaBean
        myApi.getType().enqueue(new Callback<ResponseDate>() {
            @Override
            public void onResponse(Call<ResponseDate> call, Response<ResponseDate> response) {
                //处理获取服务端数据成功
                ResponseDate responseDate = response.body();
                //定义适配器
                //初始化设置适配器
                 myPagerAdapter = new MyPagerAdapter(getFragmentManager(),responseDate.data);
                viewPager.setAdapter(myPagerAdapter);
                //设置指示器
                tabLayout.setupWithViewPager(viewPager);
            }

            @Override
            public void onFailure(Call<ResponseDate> call, Throwable t) {
                //处理获取服务端数据失败
            }
        });


    }
}

你可能感兴趣的:(仿头条APP项目)