Tablayout和Fragment联动+ListView接口变换展示

依赖:
compile 'com.android.support:design:26+'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'

权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

MainActivity主页面:
 
  
package com.bwie.wyy.myapplication;

import android.os.Bundle;
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.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager vp;
    String[] tabs =  {"推荐","热点","体育","娱乐","社会","汽车","教育","财经","科技","游戏"};
    private String[] urlS = {
            "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1",
            "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/2",
            "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/3",
            "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/4",
            "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/5",
            "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/6",
            "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/7",
            "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/8",
            "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/9",
            "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/10"
    };
    private ArrayList fragments;
    MyVpAdapter myVpAdapter;
    FragmentManager fm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //得到组件
        tabLayout = (TabLayout) findViewById(R.id.tablayout);
        vp = (ViewPager) findViewById(R.id.vp);
        fm = getSupportFragmentManager();
        //创建集合,存储vp的page页(fragment)
        fragments = new ArrayList();
        //给tablayout设置tab页
        for(int i=0;i<tabs.length;i++){
            FragmentForVp fragmentForVp = new FragmentForVp();
            Bundle b = new Bundle();
            b.putString("data",tabs[i]);
            b.putString("dataUrl",urlS[i]);
            fragmentForVp.setArguments(b);
            fragments.add(fragmentForVp);
            tabLayout.addTab(tabLayout.newTab().setText(tabs[i]));
        }
        //给vp配置page页
        myVpAdapter = new MyVpAdapter(fm);
        vp.setAdapter(myVpAdapter);
        //tablayout和vp的关联
        tabLayout.setupWithViewPager(vp);
      tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Toast.makeText(MainActivity.this,tab.getText(),Toast.LENGTH_SHORT).show();
                if(tab.getText().equals("推荐")){
                    //请求推荐的网络数据
                }else if(tab.getText().equals("热点")){
                    //请求热点的网络数据
                }else{
                }
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}
            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
    }
    class MyVpAdapter extends FragmentPagerAdapter{
        public MyVpAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }
        @Override
        public int getCount() {
            return fragments.size();
        }
        @Override
        public CharSequence getPageTitle(int position) {
            return tabs[position];
        }
    }
}



 
  
activity_main主页面布局:	
 
  
	
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:id="@+id/activity_main"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" tools:context="com.bwie.wyy.myapplication.MainActivity">

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="@android:color/holo_red_light"
        app:tabIndicatorColor="@android:color/holo_red_light"
        app:tabTextAppearance="@android:style/TextAppearance.Large"
        />
    <android.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/tablayout"/>
RelativeLayout>
 
  
 
  
 
  
 
  
 
  
FragmentForVp页面:

 
  
package com.bwie.wyy.myapplication;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import java.util.List;

public class FragmentForVp extends Fragment {
    private TextView tv;
    private String dataUrl;
    private ListView newsLv;
    private String data;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_layout,container,false);

        newsLv = (ListView) view.findViewById(R.id.newsLv);

        Bundle arguments = getArguments();//获得通过setArgument传的值
        dataUrl = getArguments().getString("dataUrl");//得到数据url
        //通过dataUrl请求网络数据,解析展示在newsLv上,扩展:实现下拉上拉效果
        new AsyncTask(){
            @Override
            protected String doInBackground(String... params) {
                NetWorkUtils netWorkUtils = new NetWorkUtils();
                data = netWorkUtils.getURL(dataUrl);
                return data;
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                Gson gson = new Gson();
                SuperClass superClass = gson.fromJson(s, SuperClass.class);
                List list = superClass.getResults();
                MyAdapter adapter = new MyAdapter(getActivity(), list);
                newsLv.setAdapter(adapter);
            }
        }.execute();
        return view;
    }
}
 
  
 
  
fragment_layout页面布局:

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"
    >
    <TextView
        android:id="@+id/tv"
        android:textSize="48dp"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <ListView
        android:id="@+id/newsLv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

LinearLayout>



NetWorkUtils工具类:

package com.bwie.wyy.myapplication;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetWorkUtils {

    public  static  String getURL(String parm){
    String data="";
        try {
            URL url = new URL(parm);
            HttpURLConnection ht = (HttpURLConnection) url.openConnection();
            ht.setConnectTimeout(5000);
            ht.setReadTimeout(5000);
            int responseCode = ht.getResponseCode();
            if(responseCode==200){
                InputStream inputStream = ht.getInputStream();
                byte[] b=new byte[1024];
                int len=0;
                while((len=inputStream.read(b))!=-1){
                    String s = new String(b, 0, len);
                    data+=s;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
}



MyAdapter  listview适配器:

package com.bwie.wyy.myapplication;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.List;
public class MyAdapter extends BaseAdapter {
    private Context context;
    private List list;

    public MyAdapter(Context context, List list) {
        this.context = context;
        this.list = list;
    }
    public int getCount() {
        return list.size();
    }
    public Object getItem(int position) {
        return list.get(position);
    }
    public long getItemId(int position) {
        return position;
    }
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView==null){
            convertView=View.inflate(context,R.layout.item,null);
            holder=new ViewHolder();
            holder.t1= (TextView) convertView.findViewById(R.id.t1);
            holder.t2= (TextView) convertView.findViewById(R.id.t2);
            holder.t3= (TextView) convertView.findViewById(R.id.t3);
            holder.t4= (TextView) convertView.findViewById(R.id.t4);
            holder.t5= (TextView) convertView.findViewById(R.id.t5);
            holder.img= (ImageView) convertView.findViewById(R.id.img);
            convertView.setTag(holder);
        }else{
            holder= (ViewHolder) convertView.getTag();
        }
        holder.t1.setText(list.get(position).getType());
        holder.t2.setText(list.get(position).getCreatedAt());
        holder.t3.setText(list.get(position).getPublishedAt());
        holder.t4.setText(list.get(position).getSource());
        holder.t5.setText(list.get(position).getUrl());
        String url=list.get(position).getUrl();
        ImageLoader.getInstance().displayImage(url,holder.img);
        return convertView;
    }
 class ViewHolder{
     TextView t1,t2,t3,t4,t5;
     ImageView img;
 }
}

 
  
Loader    ImagLoader全局配置类:(在清单文件中  name=".mapp")

package com.bwie.wyy.myapplication;

import android.app.Application;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class Loader extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoaderConfiguration build = new ImageLoaderConfiguration.Builder(this).build();
        ImageLoader.getInstance().init(build);
    }
}



SuperClass   News Bean类:

package com.bwie.wyy.myapplication;

import java.util.List;
public class SuperClass {
    private List results;
    public List getResults() {
        return results;
    }
    public void setResults(List results) {
        this.results = results;
    }
    class Bean{
        private String createdAt;
        private String publishedAt;
        private String type;
        private String source;
        private String url;
        public String getCreatedAt() {
            return createdAt;
        }
        public void setCreatedAt(String createdAt) {
            this.createdAt = createdAt;
        }
        public String getPublishedAt() {
            return publishedAt;
        }
        public void setPublishedAt(String publishedAt) {
            this.publishedAt = publishedAt;
        }
        public String getType() {
            return type;
        }
        public void setType(String type) {
            this.type = type;
        }
        public String getSource() {
            return source;
        }
        public void setSource(String source) {this.source = source;}
        public String getUrl() {
            return url;
        }
        public void setUrl(String url) {
            this.url = url;
        }
    }
}



item布局:

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">
    <TextView
        android:id="@+id/t1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/t2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/t3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/t4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/t5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ImageView
        android:id="@+id/img"
        android:layout_width="200sp"
        android:layout_height="200sp" />
LinearLayout>




你可能感兴趣的:(Tablayout和Fragment联动+ListView接口变换展示)