简介

在现在的安卓开发中,大部分需求会经常遇上viewpager和tablayout组合实现的功能,然后通过网络请求拿到数据然后显示在页面上,之前自己也在网上搜索过一些文章,要么是帮助不大,要么是效果不一样,要么是贴的代码不完整,从而导致一脑门汗呐,所以我自己在摸索了一阵之后,参考腾讯新闻的首页,完成了一个大致还算完整的demo,供大家参考。有问题还望大家指正出来,感激不尽。。

需要自定义指示器的请看第二篇:

tablayout+viewpager自定义指示器

老规矩,先贴效果图

本文先着重显示viewpager+tablayout;

下面的源码是整合后的代码,已经实现了部分新功能。

Android欢迎页跳转简易新闻列表实现 android实现新闻页面_刷新加载

使用到得控件和工具简介:

  • RefreshLayout(上拉加载下拉刷新控件)
  • Adapter(加载数据的适配器)
  • ViewPager(视图加载)
  • TabLayout(最上方的title控件)
  • Handler(网络通信)
  • Glide(图片框架)

好了,开始上代码吧!!!

首先,先导入一系列的插件:

//基本使用
    implementation 'com.android.support:design:27.0.2'
    implementation 'com.android.support:appcompat-v7:27.0.2'
    implementation 'com.android.support:cardview-v7:27.0.2'

    //图片加载
    implementation 'com.github.bumptech.glide:glide:3.7.0'

    //刷新加载框架
    implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.0.3'
    implementation 'com.scwang.smartrefresh:SmartRefreshHeader:1.0.3'

    //网络请求
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    //数据解析
    implementation 'com.google.code.gson:gson:2.8.5'
    //???
    implementation 'com.squareup.picasso:picasso:2.5.2'

当然,请求数据肯定是用到了网络,就要放入网络权限:

<uses-permission android:name="android.permission.INTERNET"/>

布局xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TabLayout
            android:id="@+id/frag_two_tabLayout"
            android:layout_width="@dimen/dimen_410_dip"
            app:tabIndicatorColor="@color/blue"
            app:tabTextColor="@color/grey"
            app:tabSelectedTextColor="@color/black"
            android:layout_height="@dimen/dimen_60_dip"
            android:background="@color/cyan"/>

        <ImageView
            android:id="@+id/frag_two_img_add"
            android:layout_width="match_parent"
            android:layout_height="@dimen/dimen_60_dip"
            android:layout_alignParentTop="true"
            android:padding="@dimen/dimen_10_dip"
            android:background="@color/cyan"
            android:layout_toEndOf="@+id/frag_two_tabLayout"
            android:src="@android:drawable/ic_menu_add"/>

    </RelativeLayout>

    <TextView
        android:id="@+id/txt_show_toast"
        android:background="@color/dodgerblue"
        android:textColor="@color/white"
        android:textSize="@dimen/dimen_14_dip"
        android:text="又为您找到了10条数据"
        android:gravity="center"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_30_dip">

    </TextView>

    <com.scwang.smartrefresh.layout.SmartRefreshLayout
        android:id="@+id/frag_two_refreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srlEnablePreviewInEditMode="false">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <android.support.v4.view.ViewPager
                android:id="@+id/frag_two_viewpager"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/white" />

            <View
                android:layout_width="match_parent"
                android:layout_height="@dimen/dimen_0.5_dip"
                android:background="@color/gainsboro" />

        </LinearLayout>

    </com.scwang.smartrefresh.layout.SmartRefreshLayout>

</LinearLayout>

MainActivity.class

/**
 * 主Activity
 * 用来显示主界面
 */
public class MainActivity extends FragmentActivity implements View.OnClickListener {

    //上下文
    Activity activity = this;

    //当前所在的fragment的值,默认为0
    public static int DEFAULTFRAGMENT = 0;

    //控件
    static ViewPager viewPager;
    TabLayout frag_two_tabLayout;
    ImageView frag_two_img_add;

    //你是多余的
    TextView txt_show_toast;

    //添加头部item布局信息
    List<String> titles = Arrays.asList("头条", "社会", "国内", "国际", "娱乐", "体育", "军事", "科技", "财经", "时尚");


    //每一个头部item所对应一个item
    static List<Frag_Two_Frag_Item> frag_two_frag_items = new ArrayList<>();

    //适配器
    static FragmentPagerAdapter fragmentPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去掉标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        //加载刷新框架
        final RefreshLayout frag_two_refreshLayout = findViewById(R.id.frag_two_refreshLayout);


        //越界回弹
        frag_two_refreshLayout.setEnableOverScrollBounce(false);

        //在刷新或者加载的时候不允许操作视图
        frag_two_refreshLayout.setDisableContentWhenRefresh(true);
        frag_two_refreshLayout.setDisableContentWhenLoading(true);

        //监听列表在滚动到底部时触发加载事件(默认true)
        frag_two_refreshLayout.setEnableAutoLoadmore(false);

        //设置自定义Header
        frag_two_refreshLayout.setHeaderHeight(50);
        frag_two_refreshLayout.setRefreshHeader(new ClassicsHeader(activity));
        //设置自定义Footer
        frag_two_refreshLayout.setFooterHeight(50);
        frag_two_refreshLayout.setRefreshFooter(new ClassicsFooter(activity));

        /**
         * 正在下拉刷新数据中
         */
        frag_two_refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                Log.i("activity", "555");
                //设置刷新事件为2s
                frag_two_refreshLayout.finishRefresh(2000);
                Frag_Two_Frag_Item.adapter.notifyDataSetChanged();
            }
        });

        /**
         * 正在上拉加载数据中
         */
        frag_two_refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                Log.i("activity", "444");
                //设置加载事件为2s
                frag_two_refreshLayout.finishLoadmore(2000);
                Frag_Two_Frag_Item.adapter.notifyDataSetChanged();
            }
        });

        /**
         * sf的事件监听
         */
        frag_two_refreshLayout.setOnMultiPurposeListener(new OnMultiPurposeListener() {
            @Override
            public void onHeaderPulling(RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {
            }

            @Override
            public void onHeaderReleasing(RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {
            }

            @Override
            public void onHeaderStartAnimator(RefreshHeader header, int headerHeight, int extendHeight) {
            }

            @Override
            public void onHeaderFinish(RefreshHeader header, boolean success) {
            }

            @Override
            public void onFooterPulling(RefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight) {
            }

            @Override
            public void onFooterReleasing(RefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight) {
            }

            @Override
            public void onFooterStartAnimator(RefreshFooter footer, int footerHeight, int extendHeight) {
            }

            @Override
            public void onFooterFinish(RefreshFooter footer, boolean success) {
            }

            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
            }

            @Override
            public void onStateChanged(RefreshLayout refreshLayout, RefreshState oldState, RefreshState newState) {
                Log.i("activity", "" + oldState + "-------" + newState);
                if(newState == RefreshState.RefreshFinish){
                    Log.i("getActivity()", "刷新完成");
                    txt_show_toast.setVisibility(View.VISIBLE);
                }
                if(oldState == RefreshState.RefreshFinish){
                    txt_show_toast.setVisibility(View.GONE);
                }
            }
        });

        //修改状态栏的颜色
        StatusBarCompat.setStatusBarColor(activity, ContextCompat.getColor(activity, R.color.cyan));

        //初始化view
        initView();
        //初始化数据
        initData();

        //通过适配器加载
        viewPager.setAdapter(fragmentPagerAdapter);
        //设置viewpager的缓存个数,全部页面都缓存
        viewPager.setOffscreenPageLimit(9);


        //必须与viewpager绑定,否则效果就看不出来
        frag_two_tabLayout.setupWithViewPager(viewPager);
        //设置tablayout的属性
        frag_two_tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        frag_two_tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    }

    /**
     * 初始化数据
     */
    private void initData() {

        //循环加载titles数组内容到fragment(每一个tablayout的显示界面都是一个frag)
        for(String title : titles){
            //通过frag对象加载title,并完成实例化
            Frag_Two_Frag_Item instance = Frag_Two_Frag_Item.getInstance(title);
            frag_two_frag_items.add(instance);
        }

        //用适配器完成每一个fragment的加载完成
        fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                //返回指定的fragment
                return frag_two_frag_items.get(position);
            }

            @Override
            public int getCount() {
                //fragment的个数
                return frag_two_frag_items.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                //将titles的内容加载进每一个(position为指定的frag)
                return titles.get(position);
            }
        };
    }

    /**
     * 初始化view
     */
    private void initView() {
        txt_show_toast = findViewById(R.id.txt_show_toast);


        //viewpager
        viewPager = findViewById(R.id.frag_two_viewpager);
        //tablayout
        frag_two_tabLayout = findViewById(R.id.frag_two_tabLayout);

        //imageview
        frag_two_img_add = findViewById(R.id.frag_two_img_add);

        //设置点击事件
        frag_two_img_add.setOnClickListener(this);

        /**
         * 设置viewpager的滑动监听事件(左右滑动)
         */
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                A.C_Log(getActivity(), "------->position=" + position);
            }

            @Override
            public void onPageSelected(int position) {
                Log.i("getActivity()", "onPageSelected----> + position=" + position);
                DEFAULTFRAGMENT = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
//                A.C_Log(getActivity(), "onPageScrollStateChanged");
            }
        });
    }

    /**
     * 设置tablayout的指示器宽度
     * @param tabs
     * @param leftDip
     * @param rightDip
     */
    @Deprecated
    public static void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

    /**
     * 单击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        int temdId = v.getId();
        if(temdId == R.id.frag_two_img_add){
            //跳转进title管理界面
            startActivity(new Intent(activity, AddTabItemActivity.class));
        }
    }

    /**
     * 将选中的值传进来并显示
     * @param SELECTEDFRAGMENT
     */
    public static void getSelectFrag(int SELECTEDFRAGMENT) {
        //跳转进viewpager指定的item
        viewPager.setCurrentItem(SELECTEDFRAGMENT, false);
    }

}

Frag_Two_Frag_Item.class

/**
 * 第一个界面里面所嵌套的公用frag
 */
public class Frag_Two_Frag_Item extends BaseFragment {

    String item_title="默认";

    public static String BUNDLE_TITLE = "title";
    public static final String APPKEY = "0bea107901b817f31bafbda687d2753d";

    public static FragTwoItemAdapter adapter;

    List<News> datas = new ArrayList<>();

    RecyclerView frag_item_listView;

    ImageView img_itemtwofrag_load;

    //获取最后一个可见view的坐标
    int lastItemPosition;
    //获取第一个可见view的坐标
    int firstItemPosition;

    /**
     * handler
     * 通过线程获取数据并加载adapter
     */
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.arg1 == 10012){
                Toast.makeText(getActivity(), R.string.getDataError, Toast.LENGTH_SHORT).show();
                return;
            }

            img_itemtwofrag_load.clearAnimation();
            img_itemtwofrag_load.setVisibility(View.GONE);
            //设置RecyclerView的数据加载
            frag_item_listView.setLayoutManager(new LinearLayoutManager(getActivity()));
            adapter = new FragTwoItemAdapter(getActivity(), datas);
            frag_item_listView.setAdapter(adapter);

            adapter.setLinster(new FragTwoItemAdapter.ItemOnClickLinster(){
                @Override
                public void textItemOnClick(View view, int position) {
                    Log.i("getActivity()", "点击事件");
                    Intent intent = new Intent(getActivity(), NewDetailActivity.class);
                    intent.putExtra("url", datas.get(position).getDateilurl());
                    intent.putExtra("img", datas.get(position).getThumbnail_pic_s());
                    intent.putExtra("title", datas.get(position).getTitle());
                    startActivity(intent);
                }
            });
        }
    };

    Map<String, String> params;


    @Override
    protected int setContentView() {
        return R.layout.frag_two_frag_item;
    }

    @Override
    protected void init() {
        Bundle bundle = getArguments();
        if(bundle != null){
            item_title = bundle.getString(BUNDLE_TITLE);
        }
        frag_item_listView = rootView.findViewById(R.id.frag_item_listView);
        img_itemtwofrag_load = rootView.findViewById(R.id.img_itemtwofrag_load);
    }

    @Override
    protected void lazyLoad() {
        img_itemtwofrag_load.setVisibility(View.VISIBLE);
        openA(getActivity(), img_itemtwofrag_load);
        handler.post(getDatas);


        frag_item_listView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState == RecyclerView.SCROLL_STATE_IDLE ){
                    Log.i("getActivity()", "这里应该是一动不动的");
                    //这里滑动停止,开始加载可见项
                    System.out.println(firstItemPosition + "   " + lastItemPosition);
                    adapter.setScrolling(false);
                    adapter.notifyDataSetChanged();
                }else if(newState == RecyclerView.SCROLL_STATE_DRAGGING){
                    Log.i("getActivity()", "这里应该是开始滑动");
                    //这里做处理(停止加载一切事情)
                    adapter.setScrolling(true);
                }else if(newState == RecyclerView.SCROLL_STATE_SETTLING){
                    Log.i("getActivity()", "这里应该是手指离开屏幕的事件");
                    //

                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                //判断是当前layoutManager是否为LinearLayoutManager
                // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                    //获取最后一个可见view的位置
                    lastItemPosition = linearManager.findLastVisibleItemPosition();
                    //获取第一个可见view的位置
                    firstItemPosition = linearManager.findFirstVisibleItemPosition();
                }
            }
        });

        //如果确定每个item的内容不会改变RecyclerView的大小,设置这个选项可以提高性能
        frag_item_listView.setHasFixedSize(true);
        frag_item_listView.setItemAnimator(new DefaultItemAnimator());

    }


    /**
     * 获取数据
     */
    Runnable getDatas = new Runnable() {
        @Override
        public void run() {
            switch (item_title){
                case "头条":
                    params = new HashMap<>();
                    params.put("key", APPKEY);
                    HttpRequest.post(HTTPURLS.toutiao, (HashMap<String, String>) params, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String reponse = response.body().string();
                            Log.i("getActivity()", "===" + reponse);
                            JsonDta(reponse);
                        }
                    });
                    break;
                case "社会":
                    params = new HashMap<>();
                    params.put("key", APPKEY);
                    HttpRequest.post(HTTPURLS.shehui, (HashMap<String, String>) params, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String reponse = response.body().string();
                            Log.i("getActivity()", "===" + reponse);
                            JsonDta(reponse);
                        }
                    });
                    break;
                case "国内":
                    params = new HashMap<>();
                    params.put("key", APPKEY);
                    HttpRequest.post(HTTPURLS.guonei, (HashMap<String, String>) params, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String reponse = response.body().string();
                            Log.i("getActivity()", "===" + reponse);
                            JsonDta(reponse);
                        }
                    });
                    break;
                case "国际":
                    params = new HashMap<>();
                    params.put("key", APPKEY);
                    HttpRequest.post(HTTPURLS.guoji, (HashMap<String, String>) params, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String reponse = response.body().string();
                            Log.i("getActivity()", "===" + reponse);
                            JsonDta(reponse);
                        }
                    });
                    break;
                case "娱乐":
                    params = new HashMap<>();
                    params.put("key", APPKEY);
                    HttpRequest.post(HTTPURLS.yule, (HashMap<String, String>) params, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String reponse = response.body().string();
                            Log.i("getActivity()", "===" + reponse);
                            JsonDta(reponse);
                        }
                    });
                    break;
                case "体育":
                    params = new HashMap<>();
                    params.put("key", APPKEY);
                    HttpRequest.post(HTTPURLS.tiyu, (HashMap<String, String>) params, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String reponse = response.body().string();
                            Log.i("getActivity()", "===" + reponse);
                            JsonDta(reponse);
                        }
                    });
                    break;
                case "军事":
                    params = new HashMap<>();
                    params.put("key", APPKEY);
                    HttpRequest.post(HTTPURLS.junshi, (HashMap<String, String>) params, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String reponse = response.body().string();
                            Log.i("getActivity()", "===" + reponse);
                            JsonDta(reponse);
                        }
                    });
                    break;
                case "科技":
                    params = new HashMap<>();
                    params.put("key", APPKEY);
                    HttpRequest.post(HTTPURLS.keji, (HashMap<String, String>) params, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String reponse = response.body().string();
                            Log.i("getActivity()", "===" + reponse);
                            JsonDta(reponse);
                        }
                    });
                    break;
                case "财经":
                    params = new HashMap<>();
                    params.put("key", APPKEY);
                    HttpRequest.post(HTTPURLS.caijing, (HashMap<String, String>) params, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String reponse = response.body().string();
                            Log.i("getActivity()", "===" + reponse);
                            JsonDta(reponse);
                        }
                    });
                    break;
                case "时尚":
                    params = new HashMap<>();
                    params.put("key", APPKEY);
                    HttpRequest.post(HTTPURLS.shishang, (HashMap<String, String>) params, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String reponse = response.body().string();
                            Log.i("getActivity()", "===" + reponse);
                            JsonDta(reponse);
                        }
                    });
                    break;
                    default :
                        break;
            }
        }
    };

    /**
     * 解析json数据
     * @param reponse
     */
    private void JsonDta(String reponse) {
        //创建对象接收返回的数据
        TwoFragData data = null;
        data = new Gson().fromJson(reponse, TwoFragData.class);
        if(data.getError_code() != 0){
            //模仿网络请求返回的参数
            Message message = handler.obtainMessage();
            message.arg1 = data.getError_code();
            handler.sendMessage(message);
        }else {
            for (int i = 0; i < data.getResult().getData().size(); i++){
                News newInfo = new News();
                newInfo.setUniquekey(data.getResult().getData().get(i).getUniquekey());
                newInfo.setTitle(data.getResult().getData().get(i).getTitle());
                newInfo.setDate(data.getResult().getData().get(i).getDate());
                newInfo.setCategory(data.getResult().getData().get(i).getCategory());
                newInfo.setAuthor_name(data.getResult().getData().get(i).getAuthor_name());
                newInfo.setDateilurl(data.getResult().getData().get(i).getUrl());
                newInfo.setThumbnail_pic_s(data.getResult().getData().get(i).getThumbnail_pic_s());
                newInfo.setThumbnail_pic_s02(data.getResult().getData().get(i).getThumbnail_pic_s02());
                newInfo.setThumbnail_pic_s03(data.getResult().getData().get(i).getThumbnail_pic_s03());
                datas.add(newInfo);
            }
            //模仿网络请求返回的参数
            Message message = handler.obtainMessage();
            handler.sendMessage(message);
        }
    }

    /**
     * 传值
     * @param item_title
     * @return
     */
    public static Frag_Two_Frag_Item getInstance(String item_title){
        Bundle bundle = new Bundle();
        bundle.putString(BUNDLE_TITLE, item_title);
        Frag_Two_Frag_Item frag_two_frag_item = new Frag_Two_Frag_Item();
        frag_two_frag_item.setArguments(bundle);
        return frag_two_frag_item;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            StatusBarCompat.setStatusBarColor(getActivity(), ContextCompat.getColor(getContext(), R.color.cyan));
        }
    }

    /**
     * 开启一个动画
     * @param img
     */
    public static void openA(Activity activity, ImageView img){
        //加载loading动画
        rotateAnimation = AnimationUtils.loadAnimation(activity, R.anim.loading);
        LinearInterpolator interpolator = new LinearInterpolator();
        rotateAnimation.setInterpolator(interpolator);
        img.startAnimation(rotateAnimation);
    }

    private static Animation rotateAnimation;

}

FragTwoItemAdapter.class

public class FragTwoItemAdapter extends RecyclerView.Adapter<FragTwoItemAdapter.ViewHolder> {

    Activity context;

    List<News> data;

    LayoutInflater inflater;

    View view;

    /**
     * 图片缓存技术的核心类,用于缓存所有下载好的图片,在程序内存达到设定值时会将最少最近使用的图片移除掉。
     */
    LruCache<String, BitmapDrawable> mMemoryCache;


    public FragTwoItemAdapter(Activity activity, List<News> datas){
        this.context = activity;
        this.data = datas;
        inflater = LayoutInflater.from(activity);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.frag_two_frag_listview_item, parent, false);
        return new ViewHolder(view);
    }

    /** 标记是否正在滑动,如果为true,就暂停加载图片 */
    protected boolean isScrolling = false;

    /**
     * 赋值
     * @param scrolling
     */
    public void setScrolling(boolean scrolling) {
        isScrolling = scrolling;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onBindViewHolder(final ViewHolder viewHolder, int position) {
        //改变item的背景
        ChangeItemBG(viewHolder);

        viewHolder.txt_title.setText(data.get(position).getTitle());
        viewHolder.txt_content.setText(data.get(position).getAuthor_name());
        viewHolder.txt_time.setText(data.get(position).getDate());

        //图片加载框架
        Glide
                .with(context)
                .load(data.get(position).getThumbnail_pic_s())
                .placeholder(R.mipmap.default_image)
                .error(R.mipmap.default_image)
                .into(viewHolder.img_icon);

    }

    /**
     * 改变背景
     * @param viewHolder
     */
    private void ChangeItemBG(ViewHolder viewHolder) {
        viewHolder.txt_title.setBackgroundResource(R.color.transparent);
        viewHolder.txt_content.setBackgroundResource(R.color.transparent);
        viewHolder.txt_time.setBackgroundResource(R.color.transparent);
        RelativeLayout.LayoutParams txt_title = (RelativeLayout.LayoutParams) viewHolder.txt_title.getLayoutParams();
        txt_title.width = LinearLayout.LayoutParams.WRAP_CONTENT;
        txt_title.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        viewHolder.txt_title.setLayoutParams(txt_title);
        LinearLayout.LayoutParams txt_content = (LinearLayout.LayoutParams) viewHolder.txt_content.getLayoutParams();
        txt_content.width = LinearLayout.LayoutParams.WRAP_CONTENT;
        txt_content.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        viewHolder.txt_content.setLayoutParams(txt_content);
        LinearLayout.LayoutParams txt_time = (LinearLayout.LayoutParams) viewHolder.txt_time.getLayoutParams();
        txt_time.width = LinearLayout.LayoutParams.WRAP_CONTENT;
        txt_time.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        viewHolder.txt_time.setLayoutParams(txt_time);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    /**
     * //自定义的ViewHolder,持有每个Item的的所有界面元素
     */
    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView txt_title, txt_content, txt_time;
        public ImageView img_icon;
        public LinearLayout lin_all;

        public ViewHolder(View rootView) {
            super(rootView);
            this.lin_all = rootView.findViewById(R.id.lin_all);
            this.img_icon = rootView.findViewById(R.id.img_icon);
            this.txt_title = rootView.findViewById(R.id.txt_title);
            this.txt_content = rootView.findViewById(R.id.txt_content);
            this.txt_time = rootView.findViewById(R.id.txt_time);

            lin_all.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Linster.textItemOnClick(v, getPosition());
                }
            });
        }
    }

    public ItemOnClickLinster Linster;

    public void setLinster(ItemOnClickLinster linster) {
        Linster = linster;
    }

    public interface ItemOnClickLinster{
        void textItemOnClick(View view, int position);
    }


}

frag_two_frag_listview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="@dimen/dimen_10_dip">

    <LinearLayout
        android:id="@+id/lin_all"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_110_dip"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/img_icon"
                android:layout_width="@dimen/dimen_85_dip"
                android:layout_height="@dimen/dimen_85_dip"
                android:layout_gravity="center"
                android:baselineAligned="false"
                android:contentDescription="TODO"
                android:scaleType="fitXY"
                android:src="@mipmap/default_image" />

        </LinearLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/dimen_85_dip"
            android:layout_marginLeft="@dimen/dimen_10_dip"
            android:orientation="vertical"
            android:layout_gravity="center">

            <TextView
                android:id="@+id/txt_title"
                android:layout_width="@dimen/dimen_100_dip"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:background="@color/gainsboro"
                android:textColor="@color/black"
                android:textSize="@dimen/dimen_18_dip" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentStart="true"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/txt_content"
                    android:layout_width="@dimen/dimen_120_dip"
                    android:layout_height="wrap_content"
                    android:background="@color/gainsboro"
                    android:gravity="center"
                    android:textColor="@color/black"
                    android:textSize="@dimen/dimen_14_dip" />

                <TextView
                    android:id="@+id/txt_time"
                    android:layout_width="@dimen/dimen_150_dip"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/dimen_15_dip"
                    android:background="@color/gainsboro"
                    android:gravity="center"
                    android:textColor="@color/black"
                    android:textSize="@dimen/dimen_14_dip" />

            </LinearLayout>

        </RelativeLayout>

    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_0.5_dip"
        android:background="@color/gainsboro" />

</LinearLayout>

其实吧,整个功能没有难懂的地方,只要理解了代码,换到自己的项目里面能够熟练的使用就可以,可以根据不同的需求去定制不同的实现方式,而这里的这种方式只是一种,给大家借鉴一下而已,同时有什么好方法也可以给我推荐下,代码的不足也可以指出!!