TabLayout与listview

xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@drawable/back"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:id="@+id/lout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <android.support.design.widget.TabLayout
            android:layout_weight="9"
            android:id="@+id/tab_out"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:tabGravity="center"
            app:tabIndicatorColor="@color/colorAccent"
            app:tabMode="scrollable"
            app:tabSelectedTextColor="@color/colorPrimaryDark"
            app:tabTextColor="@color/colorPrimary">android.support.design.widget.TabLayout>
        <Button
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="管理"
            android:id="@+id/btn_guan"/>
    LinearLayout>

    <android.support.v4.view.ViewPager
        android:layout_below="@+id/lout"
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">android.support.v4.view.ViewPager>
RelativeLayout>


-------------------------------------------------------------------------------------------------------------------------

xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ptr="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <com.handmark.pulltorefresh.library.PullToRefreshListView
        ptr:ptrDrawable="@drawable/default_ptr_flip"
        ptr:ptrAnimationStyle="flip"
        ptr:ptrHeaderBackground="#383838"
        ptr:ptrHeaderTextColor="#FFFFFF"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/plv">com.handmark.pulltorefresh.library.PullToRefreshListView>

RelativeLayout>

-------------------------------------------------------------------------------------------------------------------

package com.example.myproject.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.example.myproject.MyActivity_GuanLi;
import com.example.myproject.R;
import com.example.myproject.base.BaseFragment;
import com.example.myproject.bean.DataBean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by John on 2018/4/26 0026.
 */

public class FragmentShou extends BaseFragment {

    private View view;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ArrayList listData;
    private Button btn_gl;

    @Override
    public View getFragmentView(LayoutInflater inflater, @Nullable ViewGroup container) {
        view = inflater.inflate(R.layout.fragment_shou,container,false);
        return view;
    }

    @Override
    public void initView() {
        //获取资源id
        tabLayout = view.findViewById(R.id.tab_out);
        viewPager = view.findViewById(R.id.viewPager);
        btn_gl = view.findViewById(R.id.btn_guan);
    }

    @Override
    public void initData() {
        //创建集合用于存储菜单栏数据
        listData = new ArrayList<>();

        //初始化菜单栏数据
        initMenus();

        //设置适配器
        setShiPQ();

        tabLayout.setupWithViewPager(viewPager);
        viewPager.setOffscreenPageLimit(listData.size());//设置加载全部页面

        //添加点击事件
        btn_gl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转页面
                Intent intent = new Intent(getActivity(),MyActivity_GuanLi.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("jihe",(Serializable)listData);
                intent.putExtras(bundle);
                startActivityForResult(intent,2000);
            }
        });
    }

    private void setShiPQ() {
        viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public CharSequence getPageTitle(int position) {
                return listData.get(position).getName();
            }

            @Override
            public Fragment getItem(int position) {
                ContentFragment fragment = new ContentFragment();
                //传参
                Bundle bundle = new Bundle();
                bundle.putString("url",listData.get(position).getMyUrl());
                fragment.setArguments(bundle);
                return fragment;
            }

            @Override
            public int getCount() {
                return listData.size();
            }
        });
    }

    private void initMenus() {
        listData.add(new DataBean("推荐","http://api.tianapi.com/nba/?key=55acaf346503d8d5f98af8dec90ceb01&num=10"));
        listData.add(new DataBean("热点","http://api.tianapi.com/it/?key=55acaf346503d8d5f98af8dec90ceb01&num=10"));
        listData.add(new DataBean("北京","http://api.tianapi.com/guonei/?key=55acaf346503d8d5f98af8dec90ceb01&num=10"));
        listData.add(new DataBean("视频","http://api.tianapi.com/vr/?key=55acaf346503d8d5f98af8dec90ceb01&num=10"));
        listData.add(new DataBean("社会","http://api.tianapi.com/social/?key=55acaf346503d8d5f98af8dec90ceb01&num=10"));
        listData.add(new DataBean("科技","http://api.tianapi.com/keji/?key=55acaf346503d8d5f98af8dec90ceb01&num=10"));
        listData.add(new DataBean("汽车","http://api.tianapi.com/startup/?key=55acaf346503d8d5f98af8dec90ceb01&num=10"));
        listData.add(new DataBean("体育","http://api.tianapi.com/tiyu/?key=55acaf346503d8d5f98af8dec90ceb01&num=10"));
        listData.add(new DataBean("财经","http://api.tianapi.com/world/?key=55acaf346503d8d5f98af8dec90ceb01&num=10"));
        listData.add(new DataBean("娱乐","http://api.tianapi.com/huabian/?key=55acaf346503d8d5f98af8dec90ceb01&num=10"));

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //判断结果码  请求码
        if(requestCode == 2000 && resultCode == 1000){
            //接受传过来的值
            listData.clear();
            ArrayList xlist = (ArrayList) data.getSerializableExtra("xjh");
            listData.addAll(xlist);
            for (int i = 0; i < listData.size(); i++) {
                Log.d("cccc", "onActivityResult: "+listData.get(i).getMyUrl());
            }
            setShiPQ();
        }
    }
}

-----------------------------------------------------------------------------------------------------------------------------

package com.example.myproject.fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myproject.R;
import com.example.myproject.base.BaseFragment;
import com.example.myproject.base.MyBase_List;
import com.example.myproject.db.UserDao;
import com.example.myproject.gson.MyGson;
import com.example.myproject.utile.NetStateUtil;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by John on 2018/4/26 0026.
 */

public class ContentFragment extends BaseFragment {

    private View view;
    private TextView textView;
    private PullToRefreshListView plv;

    private int pageIndex = 1;
    private int clickType = 1;
    private String url;
    private String myUrl;

    private List newslists = new ArrayList<>();
    private MyBase_List base_list;
    private UserDao userDao;

    @Override
    public View getFragmentView(LayoutInflater inflater, @Nullable ViewGroup container) {
        view = inflater.inflate(R.layout.contentfragment,container,false);
        return view;
    }

    @Override
    public void initView() {
        //获取资源id
        plv = view.findViewById(R.id.plv);
    }

    @Override
    public void initData() {

        //创建数据库的逻辑操作类
        userDao = new UserDao(getActivity());


        //初始化PullToRefreshListView
        initPlv();
        //接收数据
        Bundle arguments = getArguments();
        if(arguments!=null){
            url = arguments.getString("url");
            //textView.setText(url);
            Log.d("zzzz", "doInBackground: "+url);
            //请求数据
            requestDataFunction();
        }


    }

    private void requestDataFunction() {
        myUrl = url+"&page="+pageIndex;
        //判断有没有网络
        if(NetStateUtil.isConn(getActivity())){
            new MyTask().execute(myUrl);

        }else {
            Toast.makeText(getActivity(), "当前没有网络", Toast.LENGTH_SHORT).show();
            //从数据库中取数据
            String selects = userDao.selects(myUrl);
            //展示数据
            showData(selects);
        }


    }

    private void initPlv() {
        plv.setMode(PullToRefreshBase.Mode.BOTH);
        plv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase pullToRefreshBase) {
                //下拉刷新
                pageIndex = 1;
                clickType = 1;
                myUrl = url+"&page="+pageIndex;
                //请求数据
                requestDataFunction();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase pullToRefreshBase) {
                //上拉加载
                pageIndex ++;
                clickType = 2;
                myUrl = url+"&page="+pageIndex;
                //请求数据
                requestDataFunction();
            }
        });
    }
    class MyTask extends AsyncTask{

        @Override
        protected String doInBackground(String... strings) {
            String string = strings[0];
            Log.d("zzzz", "doInBackground: "+string);
            try {
                URL url = new URL(strings[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setConnectTimeout(5000);
                urlConnection.setReadTimeout(5000);
                if(urlConnection.getResponseCode() == 200){
                    InputStream inputStream = urlConnection.getInputStream();
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    int len;
                    byte[] b = new byte[1024];
                    while ((len = inputStream.read(b))!=-1){
                        outputStream.write(b,0,len);
                    }
                    return outputStream.toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //网数据库中存数据
            userDao.add(myUrl,s);

            //展示数据
            showData(s);
        }
    }

    private void showData(String s) {
        if (!s.equals("")) {
            Gson gson = new Gson();
            MyGson myGson = gson.fromJson(s, MyGson.class);
            List newslist = myGson.getNewslist();
            if(newslist==null){
                Toast.makeText(getActivity(), "没有数据了", Toast.LENGTH_SHORT).show();
            }else {
                if(clickType == 1){
                    newslists.clear();
                }
                newslists.addAll(newslist);
                //设置适配器
                setShiPeiQi();
            }

        }
        //关闭头尾视图
        plv.onRefreshComplete();
    }

    private void setShiPeiQi() {
        //newslists
        if (base_list==null) {
            base_list = new MyBase_List(getActivity(),newslists);
            plv.setAdapter(base_list);
        } else {
            base_list.notifyDataSetChanged();
        }
    }
}

你可能感兴趣的:(TabLayout与listview)