侧拉+pullToRefresh+无限轮播+tabLayout+fragment

来源:互联网 发布:淘宝售后人员工作流程 编辑:程序博客网 时间:2024/05/18 00:00

activity_main

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.bawei.w.wanghongyun20171025.MainActivity">

    <android.support.v4.widget.DrawerLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <RelativeLayout
            android:layout_width="250dp"
            android:layout_height="match_parent"
            android:layout_gravity="left"
            android:background="#fff">

            <ImageView
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:id="@+id/img"
                android:padding="10dp"
                android:src="@mipmap/ic_launcher"/>

            <TextView
                android:id="@+id/grsz"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/img"
                android:padding="10dp"
                android:text="个人设置" />

            <TextView
                android:id="@+id/hc"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/grsz"
                android:padding="10dp"
                android:text="缓存" />

            <TextView
                android:id="@+id/yjms"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/hc"
                android:padding="10dp"
                android:text="夜间模式" />

            <TextView
                android:id="@+id/pz"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/yjms"
                android:padding="10dp"
                android:text="配置" />
        </RelativeLayout>
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/ll"
                android:orientation="horizontal"
                android:gravity="center"
                android:layout_alignParentBottom="true">
                <Button
                    android:id="@+id/shouye"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="首页" />

                <Button
                    android:id="@+id/fenlei"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="分类" />

                <Button
                    android:id="@+id/faxian"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="发现" />

                <Button
                    android:id="@+id/gowuche"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="购物车" />

                <Button
                    android:id="@+id/wode"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="我的" />
    </LinearLayout>
            <FrameLayout
            android:id="@+id/frag"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/ll"></FrameLayout>
        </RelativeLayout>
    </android.support.v4.widget.DrawerLayout>

</android.support.constraint.ConstraintLayout>

faxian

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

    <android.support.design.widget.TabLayout
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fillViewport="false"
        app:tabIndicatorColor="#052efc"
        app:tabIndicatorHeight="5dp"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="#f9ec03"
        app:tabTextColor="#f204ce"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/tab"/>
</LinearLayout>

fragmentss

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

    <com.jwenfeng.library.pulltorefresh.PullToRefreshLayout
        android:id="@+id/pull_1"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
            android:id="@+id/list_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></ListView>

    </com.jwenfeng.library.pulltorefresh.PullToRefreshLayout>
</LinearLayout>
item

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

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/img1"
        android:src="@mipmap/ic_launcher" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv1"
        android:layout_below="@id/img1"
        android:text="aaaaaaa"/>
</RelativeLayout>

item2

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_weight="2"
        android:id="@+id/tv01"
        android:text="aaaaaaaaaa"/>
    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:id="@+id/img01"
        android:src="@mipmap/ic_launcher"/>
</LinearLayout>

item3

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv02"
        android:text="aaaaaaaaaa"/>
    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/img02"
        android:layout_below="@id/tv02"
        android:src="@mipmap/ic_launcher"/>
</RelativeLayout>

shouye

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

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    <com.bigkoo.convenientbanner.ConvenientBanner
        android:id="@+id/con"
        android:layout_width="match_parent"
        android:layout_height="250dp"/>
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    <com.jwenfeng.library.pulltorefresh.PullToRefreshLayout
        android:id="@+id/pull_1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">

        <GridView
            android:id="@+id/grid_view"
            android:layout_width="match_parent"
            android:numColumns="2"
            android:layout_height="match_parent"/>

    </com.jwenfeng.library.pulltorefresh.PullToRefreshLayout>
    </RelativeLayout>
</LinearLayout>


MainActivity.java

package com.bawei.w.wanghongyun20171025;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Button shouye;
    private Button fenlei;
    private Button faxian;
    private Button gowuche;
    private Button wode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (isNetworkAvailable(MainActivity.this)) {
            Toast.makeText(getApplicationContext(), "当前有可用网络!", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "当前没有可用网络!", Toast.LENGTH_LONG).show();
        }
        shouye = (Button) findViewById(R.id.shouye);
        fenlei = (Button) findViewById(R.id.fenlei);
        faxian = (Button) findViewById(R.id.faxian);
        gowuche = (Button) findViewById(R.id.gowuche);
        wode = (Button) findViewById(R.id.wode);

        //初始化界面
        FragmentManager manager = getSupportFragmentManager();

        FragmentTransaction transaction = manager.beginTransaction();

        transaction.replace(R.id.frag, new Shouye());

        transaction.commit();

        shouye.setBackgroundColor(Color.BLUE);
        fenlei.setBackgroundColor(Color.WHITE);
        faxian.setBackgroundColor(Color.WHITE);
        gowuche.setBackgroundColor(Color.WHITE);
        wode.setBackgroundColor(Color.WHITE);

        shouye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //首页
                FragmentManager manager = getSupportFragmentManager();

                FragmentTransaction transaction = manager.beginTransaction();

                transaction.replace(R.id.frag, new Shouye());

                transaction.commit();

                shouye.setBackgroundColor(Color.BLUE);
                fenlei.setBackgroundColor(Color.WHITE);
                faxian.setBackgroundColor(Color.WHITE);
                gowuche.setBackgroundColor(Color.WHITE);
                wode.setBackgroundColor(Color.WHITE);
            }
        });

        //按钮的点击事件
        fenlei.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //自选页
                FragmentManager manager = getSupportFragmentManager();

                FragmentTransaction transaction = manager.beginTransaction();

                transaction.replace(R.id.frag, new Fenlei());

                transaction.commit();

                shouye.setBackgroundColor(Color.WHITE);
                fenlei.setBackgroundColor(Color.BLUE);
                faxian.setBackgroundColor(Color.WHITE);
                gowuche.setBackgroundColor(Color.WHITE);
                wode.setBackgroundColor(Color.WHITE);

            }

        });

        //按钮的点击事件
        faxian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //行情页
                FragmentManager manager = getSupportFragmentManager();

                FragmentTransaction transaction = manager.beginTransaction();

                transaction.replace(R.id.frag, new Faxian());

                transaction.commit();
                shouye.setBackgroundColor(Color.WHITE);
                fenlei.setBackgroundColor(Color.WHITE);
                faxian.setBackgroundColor(Color.BLUE);
                gowuche.setBackgroundColor(Color.WHITE);
                wode.setBackgroundColor(Color.WHITE);

            }

        });

        //按钮的点击事件
        gowuche.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //资讯页
                FragmentManager manager = getSupportFragmentManager();

                FragmentTransaction transaction = manager.beginTransaction();

                transaction.replace(R.id.frag, new Gowuche());

                transaction.commit();
                shouye.setBackgroundColor(Color.WHITE);
                fenlei.setBackgroundColor(Color.WHITE);
                faxian.setBackgroundColor(Color.WHITE);
                gowuche.setBackgroundColor(Color.BLUE);
                wode.setBackgroundColor(Color.WHITE);

            }

        });

        //按钮的点击事件
        wode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //交易页
                FragmentManager manager = getSupportFragmentManager();

                FragmentTransaction transaction = manager.beginTransaction();

                transaction.replace(R.id.frag, new Wode());

                transaction.commit();
                shouye.setBackgroundColor(Color.WHITE);
                fenlei.setBackgroundColor(Color.WHITE);
                faxian.setBackgroundColor(Color.WHITE);
                gowuche.setBackgroundColor(Color.WHITE);
                wode.setBackgroundColor(Color.BLUE);

            }

        });

    }

    /**
     * 检查当前网络是否可用
     *
     * @return
     */

    public boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    System.out.println(i + "===状态===" + networkInfo[i].getState());
                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}


Shouye.java

package com.bawei.w.wanghongyun20171025;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.PullToRefreshLayout;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * Created by W on 2017/10/25.
 */

public class Shouye extends Fragment implements OnItemClickListener{
    private ConvenientBanner con;
    //获取网络图片
    private String[] imags = new String[]{
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1505466935727&di=cc628863f867635385d47a1fdc7866ba&imgtype=0&src=http%3A%2F%2Fa2.att.hudong.com%2F03%2F25%2F300000928390129248252247558.jpg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1505466963806&di=03d7ff59f83939cd98d29ad5d65ae696&imgtype=0&src=http%3A%2F%2Fk.zol-img.com.cn%2Fdcbbs%2F17173%2Fa17172908_01000.jpg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1505466985467&di=6c9d023769bbe2b9ec7b897c1e7b2f23&imgtype=0&src=http%3A%2F%2Fk.zol-img.com.cn%2Fdcbbs%2F17173%2Fa17172874_01000.jpg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1505467008837&di=d6a7f3459f05443fa0d940885bfadac8&imgtype=jpg&src=http%3A%2F%2Fimg3.imgtn.bdimg.com%2Fit%2Fu%3D2339828535%2C1196971278%26fm%3D214%26gp%3D0.jpg"};

    private String path;
    private int shu = 10;
    private GridView gv;
    private PullToRefreshLayout pull_1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                JsonBean bean = (JsonBean) msg.obj;
                list = bean.getNewslist();
                Log.i("aaa", list.toString());
                myad = new Myad();
                gv.setAdapter(myad);
            }

        }
    };
    List<String> datas;
    ImageLoader imageLoader;
    private Myad myad;
    private List<JsonBean.NewslistBean> list;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = View.inflate(getActivity(), R.layout.shouye_layout, null);
        gv = (GridView) v.findViewById(R.id.grid_view);
        pull_1 = (PullToRefreshLayout) v.findViewById(R.id.pull_1);
        con = (ConvenientBanner) v.findViewById(R.id.con);
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()));
        datas = Arrays.asList(imags);
        //开启自动翻页
        con.setPages(new CBViewHolderCreator() {
            @Override
            public Object createHolder() {
                return new Myhoude();
            }
        }, datas);

        //设置指示器是否可见
        con.setPointViewVisible(true);
        //设置自动切换,同时设置切换间隔时间
        con.startTurning(2000);
        //设置点击监听事件
        con.setOnItemClickListener(this);
        //设置两个 点图片 作为翻页指示器
        con.setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused});
        //设置指示器的方向(左,中,右)
        con.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
        //设置手动影响
        con.setManualPageable(true);

        getdata();

        pull_1.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        path = "http://api.tianapi.com/keji/?key=51f42ae57be18f5f5d7b402ef0bc64aa&num=" + (shu++);
                        getdata();
                        myad.notifyDataSetChanged();
                        pull_1.finishRefresh();
                    }
                }, 3000);
            }

            @Override
            public void loadMore() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        path = "http://api.tianapi.com/keji/?key=51f42ae57be18f5f5d7b402ef0bc64aa&num=" + (shu++);
                        getdata();
                        myad.notifyDataSetChanged();

                        pull_1.finishLoadMore();
                    }
                }, 3000);
            }
        });
        return v;
    }

    class Myad extends BaseAdapter {

        private final int lin = 0;
        private final int one = 1;

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

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            ViewHolder holder;
            if (view==null){
                view=View.inflate(getActivity(),R.layout.item_layout,null);
                holder=new ViewHolder();
                holder.img1= (ImageView) view.findViewById(R.id.img1);
                holder.tv1= (TextView) view.findViewById(R.id.tv1);
                view.setTag(holder);
            }else {
                holder= (ViewHolder) view.getTag();
            }
            holder.tv1.setText(list.get(i).getTitle());
            ImageLoader.getInstance().displayImage(list.get(i).getPicUrl(),holder.img1);

            return view;
        }

        class ViewHolder{
            ImageView img1;
            TextView tv1;
        }
    }

    @Override
    public void onItemClick(int position) {

    }

    private class Myhoude implements Holder<String> {

        ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, String data) {
            ImageLoader.getInstance().displayImage(data, imageView);
        }
    }

    public int getid(String name, Class<?> c) {
        Field field = null;
        try {
            field = c.getDeclaredField(name);
            return field.getInt(field);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    private void getdata() {
        new Thread() {
            @Override
            public void run() {
                if (path == null) {
                    path = "http://api.tianapi.com/keji/?key=51f42ae57be18f5f5d7b402ef0bc64aa&num=" + shu;
                }
                try {
                    URL url = new URL(path);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setReadTimeout(5000);
                    connection.setConnectTimeout(5000);
                    if (connection.getResponseCode() == 200) {
                        InputStream stream = connection.getInputStream();
                        String json = zhuan(stream, "utf-8");
                        Log.i("aaa", json);
                        Gson gson = new Gson();
                        JsonBean fromJson = gson.fromJson(json, JsonBean.class);
                        Log.i("aaa", "aaaaaa");
                        Message message = Message.obtain();
                        message.what = 0;
                        message.obj = fromJson;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.run();
            }
        }.start();
    }

    private String zhuan(InputStream stream, String s) {
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(stream, s);
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String ss = null;
            StringBuilder builder = new StringBuilder();
            while ((ss = reader.readLine()) != null) {
                builder.append(ss);
            }
            inputStreamReader.close();
            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

faxian.java

package com.bawei.w.wanghongyun20171025;

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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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

/**
 * Created by W on 2017/10/25.
 */

public class Faxian extends Fragment {
    //全局变量
    TabLayout tab;

    private List<String> list;

    ViewPager vp;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        //初始化视图
        View v = View.inflate(getActivity(), R.layout.faxian_layout, null);

        //初始化控件
        tab = (TabLayout) v.findViewById(R.id.tab);

        vp = (ViewPager) v.findViewById(R.id.vp);

        //创建集合
        list = new ArrayList<>();

        //向集合中添加数据
        list.add("精选");
        list.add("英伦风");
        list.add("直播");
        list.add("订阅");
        list.add("视频购");
        list.add("问答");

        //ViewPager的监听事件
        vp.setAdapter(new FragmentPagerAdapter(getActivity().getSupportFragmentManager()) {

            @Override
            public CharSequence getPageTitle(int position) {
                return list.get(position);
            }

            @Override
            public Fragment getItem(int position) {

                //获取数据
                Fragmentss fragmentss = new Fragmentss();

                Bundle bundle = new Bundle();

                //判断
                if (list.get(position).endsWith("精选")) {
                    bundle.putString("name", "keji");
                } else if (list.get(position).endsWith("英伦风")) {
                    bundle.putString("name", "startup");
                } else if (list.get(position).endsWith("直播")) {
                    bundle.putString("name", "apple");
                } else if (list.get(position).endsWith("订购")) {
                    bundle.putString("name", "it");
                } else if (list.get(position).endsWith("视频购")) {
                    bundle.putString("name", "vr");
                } else if (list.get(position).endsWith("问答")) {
                    bundle.putString("name", "health");
                }

                //传递数据
                fragmentss.setArguments(bundle);

                return fragmentss;
            }

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

        });

        //绑定
        tab.setupWithViewPager(vp);

        //返回视图
        return v;
    }
}

Fragmentss.java

package com.bawei.w.wanghongyun20171025;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.PullToRefreshLayout;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * Created by W on 2017/10/25.
 */

public class Fragmentss extends Fragment{
    PullToRefreshLayout pull;
    ListView pull_lv;
    private String s;
    private int shu = 10;
    private String path;
    List<JsonBean.NewslistBean> list;
    MyAdapter myAdapter;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 0) {

                JsonBean bean = (JsonBean) msg.obj;

                list = bean.getNewslist();
                Log.i("aaa",list.toString());
                myAdapter = new MyAdapter();

                pull_lv.setAdapter(myAdapter);

            }

        }

    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = View.inflate(getActivity(), R.layout.fragmentss_layout, null);

        pull = (PullToRefreshLayout) v.findViewById(R.id.pull_1);

        pull_lv = (ListView) v.findViewById(R.id.list_view);

        Bundle bundle = getArguments();

        s = bundle.getString("name", "social");

        getdata(s);

        pull.setRefreshListener(new BaseRefreshListener() {

            @Override
            public void refresh() {

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        shu++;
                        path = "http://api.tianapi.com/"+s+"/?key=51f42ae57be18f5f5d7b402ef0bc64aa&num=" + shu;
                        getdata(s);
                        myAdapter.notifyDataSetChanged();
                        pull.finishRefresh();

                    }
                }, 3000);

            }

            @Override
            public void loadMore() {

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        shu++;
                        path = "http://api.tianapi.com/"+s+"/?key=51f42ae57be18f5f5d7b402ef0bc64aa&num=" + shu;
                        getdata(s);
                        myAdapter.notifyDataSetChanged();
                        pull.finishLoadMore();

                    }
                }, 3000);

            }

        });

        return v;
    }

    private void getdata(final String s) {
        new Thread() {

            @Override
            public void run() {

                path = "http://api.tianapi.com/"+s+"/?key=51f42ae57be18f5f5d7b402ef0bc64aa&num=" + shu;

                try {

                    URL url = new URL(path);

                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    connection.setRequestMethod("GET");

                    connection.setReadTimeout(5000);

                    connection.setConnectTimeout(5000);

                    if (connection.getResponseCode() == 200) {

                        InputStream stream = connection.getInputStream();

                        String json = zhuan(stream, "utf-8");
                        Log.i("aaa",json);
                        Gson gson = new Gson();

                        JsonBean fromJson = gson.fromJson(json, JsonBean.class);

                        Message message = Message.obtain();

                        message.what = 0;

                        message.obj = fromJson;

                        handler.sendMessage(message);

                    }

                } catch (Exception e) {

                    e.printStackTrace();

                }

            }

        }.start();
    }

    private String zhuan(InputStream stream, String s) {

        try {

            InputStreamReader inputStreamReader = new InputStreamReader(stream, s);

            BufferedReader reader = new BufferedReader(inputStreamReader);

            String ss = null;

            StringBuilder builder = new StringBuilder();

            while ((ss = reader.readLine()) != null) {

                builder.append(ss);

            }

            inputStreamReader.close();

            return builder.toString();

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

    class MyAdapter extends BaseAdapter {

        private final int lin = 0;
        private final int one = 1;

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

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            int type = getItemViewType(i);

            Diyi diyi;

            Dier dier;

            switch (type) {

                case lin:

                    if (view == null) {
                        view = View.inflate(getActivity(), R.layout.item2_layout, null);
                        diyi = new Diyi();
                        diyi.yiimg1 = (ImageView) view.findViewById(R.id.img01);
                        diyi.yitext = (TextView) view.findViewById(R.id.tv01);
                        view.setTag(diyi);
                    }
                    break;

                case one:

                    if (view == null) {
                        view = View.inflate(getActivity(), R.layout.item3_layout, null);
                        dier = new Dier();
                        dier.ertext = (TextView) view.findViewById(R.id.tv02);
                        dier.erimg1 = (ImageView) view.findViewById(R.id.img02);
                        view.setTag(dier);
                    }

                    break;

                default:

                    break;

            }

            switch (type) {

                case lin:

                    diyi = (Diyi) view.getTag();
                    diyi.yitext.setText(list.get(i).getTitle());
                    ImageLoader.getInstance().displayImage(list.get(i).getPicUrl(), diyi.yiimg1);

                    break;

                case one:

                    dier = (Dier) view.getTag();
                    dier.ertext.setText(list.get(i).getTitle());
                    ImageLoader.getInstance().displayImage(list.get(i).getPicUrl(), dier.erimg1);

                    break;

                default:

                    break;

            }

            return view;
        }

        @Override
        public int getItemViewType(int position) {

            int i = position % 2;

            if (i == 0) {
                return 0;
            } else {
                return 1;
            }

        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        class Diyi {
            ImageView yiimg1;
            TextView yitext;
        }

        class Dier {
            TextView ertext;
            ImageView erimg1;
        }

    }

}








阅读全文
1 0
原创粉丝点击