Android TabLayout和ViewPager配套的简单使用

首先是导依赖
    compile 'com.android.support:design:26.0.0-alpha1'
    compile 'com.jwenfeng.pulltorefresh:library:1.0.3'
    compile 'com.bigkoo:convenientbanner:2.0.5'
接下来是TabLayout和ViewPager布局视图
<?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"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.example.app2_work.MainActivity"
    tools:showIn="@layout/app_bar_main">
     <android.support.design.widget.TabLayout
         android:layout_width="match_parent"
         android:layout_height="30dp"
         android:id="@+id/tabs"
         android:layout_alignParentTop="true"
         app:tabMode="scrollable"
         app:tabSelectedTextColor="@color/slect"
         app:tabIndicatorColor="@color/slect"
         app:tabIndicatorHeight="3dp"
         app:tabGravity="center"
         ></android.support.design.widget.TabLayout>
    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/vp"
        android:layout_below="@id/tabs"
        ></android.support.v4.view.ViewPager>
</RelativeLayout>

给TabLayout和ViewPager建立联动

package com.example.app2_work;

import android.os.Bundle;
import android.support.design.widget.NavigationView;
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.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private TabLayout tabs;
    private ViewPager vps;
    private List<String> arrylist = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        init();
        getinit();
        tabs.setupWithViewPager(vps);
    }
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    private void init() {
        tabs = (TabLayout) findViewById(R.id.tabs);
        vps = (ViewPager) findViewById(R.id.vp);
        arrylist.add("美女");
        arrylist.add("VR");
        arrylist.add("国际");
        arrylist.add("娱乐");
        arrylist.add("体育");
        arrylist.add("NBA");
        arrylist.add("足球");
        arrylist.add("科技");
        arrylist.add("创业");
        arrylist.add("苹果");
    }
    private void getinit() {
        MyAdapter adapter = new MyAdapter(getSupportFragmentManager());
        vps.setAdapter(adapter);
    }
    class MyAdapter extends FragmentPagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public CharSequence getPageTitle(int position) {
            return arrylist.get(position);
        }
        @Override
        public Fragment getItem(int position) {
            Frag1 frag1 = new Frag1();
            Bundle bundle = new Bundle();
            if (arrylist.get(position).equals("美女")) {
                bundle.putString("name","meinv");
            }else if (arrylist.get(position).equals("VR")){
                bundle.putString("name","vr");
            }else if (arrylist.get(position).equals("国际")) {
                bundle.putString("name","world");
            }else if (arrylist.get(position).equals("娱乐")) {
                bundle.putString("name","huabian");
            }else if (arrylist.get(position).equals("体育")) {
                bundle.putString("name","tiyu");
            }else if (arrylist.get(position).equals("NBA")) {
                bundle.putString("name","nba");
            }else if (arrylist.get(position).equals("足球")) {
                bundle.putString("name","football");
            }else if (arrylist.get(position).equals("科技")) {
                bundle.putString("name","keji");
            }else if (arrylist.get(position).equals("创业")) {
                bundle.putString("name","startup");
            }else if (arrylist.get(position).equals("苹果")) {
                bundle.putString("name","apple");
            }
            frag1.setArguments(bundle);
            return frag1;
        }
        @Override
        public int getCount() {
            return arrylist.size();
        }
    }
}
然后建立一个类继承Fragment,用来接收从主页面传来的数据,并通过异步任务进行网络请求获取数据,通过Gson解析封装到List集合中,把集合中的数据赋给适配器,并添加适配器,从而显示出来;
Fragment布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.handmark.pulltorefresh.library.PullToRefreshListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/plv"
        android:layout_below="@id/tabs"
        ></com.handmark.pulltorefresh.library.PullToRefreshListView>
</RelativeLayout>
Fragment页面中获取数据:
package com.example.app2_work;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
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.AdapterView;
import android.widget.ListView;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import Bean.JsonRootBean;
import Bean.Newslist;
/**
 * Created by ZhangTAO on 2017/9/20.
 */

public class Frag1 extends Fragment{
    private String names;
    private int nub = 10;
    private List<Newslist> datas;
    private MyAdapterzt myAdapterzt;
    private Handler ler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                myAdapterzt.notifyDataSetChanged();
                plv.onRefreshComplete();
            }
            if (msg.what == 0) {
                myAdapterzt.notifyDataSetChanged();
                plv.onRefreshComplete();
            }
        }
    };
    private PullToRefreshListView plv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v1 = inflater.inflate(R.layout.frag1_act, null);
        plv = v1.findViewById(R.id.plv);
        return v1;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle arguments = getArguments();
        names = arguments.getString("name");
        if (isNetWorkInif()) {
            getDatamatFor(names);
        }else {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("警告!");
            builder.setMessage("网络不可用,是否设置?");
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                    startActivity(intent);
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                }
            });
            builder.show();
        }
    }
    /**
     * 判断网络连接
     * @return
     */
    private boolean isNetWorkInif() {
        ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info != null) {
            return info.isAvailable();
        }
        return false;
    }
    /**
     * 异步任务
     * @param string
     */
    private void getDatamatFor(final String string) {
        AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {
                getDat(string);
                return null;
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                myAdapterzt = new MyAdapterzt(getActivity(), datas);
                plv.setAdapter(myAdapterzt);
                plv.setMode(PullToRefreshBase.Mode.BOTH);
                plv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                    @Override
                    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                nub=10;
                                getDatamatFor(names);
                                ler.sendEmptyMessageDelayed(1,2000);
                            }
                        }).start();
                    }

                    @Override
                    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                nub=nub+5;
                                getDatamatFor(names);
                                ler.sendEmptyMessageDelayed(0,2000);
                            }
                        }).start();
                    }
                });
                 plv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                     @Override
                     public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                         Intent intent = new Intent(getActivity(), Main2.class);
                         startActivity(intent);
                     }
                 });
            }
        };
        task.execute();
    }
    /**
     * 获取网络数据
     */
    public void getDat(String name) {
        String json = null;
        String path = "http://api.tianapi.com/"+name+"/?key=c8bb8de75b2287a6c6c390c50afb21e1&num="+nub;
        try {
            URL url = new URL(path);
            HttpURLConnection connection = null;
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            int code = connection.getResponseCode();
            if (code == 200) {
                InputStream inputStream = connection.getInputStream();
                json = streamTostring(inputStream, "utf-8");
                Gson gs = new Gson();
                JsonRootBean fromJson = gs.fromJson(json.toString(), JsonRootBean.class);
                datas = fromJson.getNewslist();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public String streamTostring(InputStream input,String charset) {
        String con = null;
        InputStreamReader inputStreamReader = new InputStreamReader(input);
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(inputStreamReader);
        try {
            while ((con = reader.readLine()) != null) {
                builder.append(con);
            }
            return builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
接下来就是适配器的设置:
适配器的两个布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/img1"
        android:layout_alignParentLeft="true"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv1"
        android:layout_toRightOf="@+id/img1"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="8dp"
        />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/title2"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="15dp"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/desc2"
        android:layout_below="@id/title2"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="40dp"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ct2"
        android:layout_below="@id/title2"
        android:layout_toRightOf="@id/desc2"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="40dp"
        />
</RelativeLayout>
适配器设置完后,就可以显示了,代码中还用了PullTOrefreshListView控件,所以ListView列表中还具有下拉刷新和上拉加载的功能;

以上是效果图的展示,在ListView中还加了条目点击事件,点击之后跳入下一个页面:
第二个页面布局视图:
<?xml version="1.0" encoding="utf-8"?>
<com.jwenfeng.library.pulltorefresh.PullToRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/mpull"
    >
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <com.bigkoo.convenientbanner.ConvenientBanner
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:id="@+id/banner"
            android:layout_alignParentTop="true"
            app:canLoop="true"
            ></com.bigkoo.convenientbanner.ConvenientBanner>
        <GridView
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:id="@+id/rd"
            android:numColumns="4"
            android:layout_below="@+id/banner"
            android:horizontalSpacing="5dp"
            android:verticalSpacing="5dp"
            ></GridView>
        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/lv"
            android:layout_below="@+id/rd"
            >
        </ListView>
    </RelativeLayout>
</com.jwenfeng.library.pulltorefresh.PullToRefreshLayout>
因为要使整个View视图具有上载下刷功能,所以使用了PullTorefreshLayout进行实现功能,其中还有从网络数据接口中获取的图片进行图片轮播,使用了ConvenientBanner,本篇刚开使写了它的依赖包,下面还有GirdView列表和ListView列表:

下面写了用异步任务请求网络数据并取出6张图片去无限轮播,并将集合赋值给GirdView和ListView的两个适配器,并设置适配器。

package com.example.app2_work;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
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.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import Bean.JsonRootBean;
import Bean.Newslist;

/**
 * Created by ZhangTAO on 2017/9/20.
 */
public class Main2 extends AppCompatActivity{
    public List<String> datalist = new ArrayList<String>();
    private ConvenientBanner banner;
    private ImageLoader imageLoader;
    private ImageView imageView;
    private String picUrl;
    private GridView rd;
    private ListView lv;
    private int nub = 15;
    private List<Newslist> newslist = new ArrayList<>();
    private Handler ler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                for (int i = 0; i < 6; i++) {
                    datalist.add(newslist.get(i).getPicUrl());
                }
            }
            getinit();
            if (msg.what == 0x1) {
                lvAdapterzt.notifyDataSetChanged();
                grAdapter.notifyDataSetChanged();
                mpull.finishRefresh();
            }
            if (msg.what == 0x2) {
                lvAdapterzt.notifyDataSetChanged();
                grAdapter.notifyDataSetChanged();
                mpull.finishLoadMore();
            }
        }
    };
    private PullToRefreshLayout mpull;
    private LvAdapterzt lvAdapterzt;
    private GrAdapter grAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2_act);
        init();
        getDataFoamat();
        ler.sendEmptyMessageDelayed(0,1000);
    }
    /**
     * 制造数据
     */
    public void getDat() {
        String json = null;
        String path = "http://api.tianapi.com/nba/?key=c8bb8de75b2287a6c6c390c50afb21e1&num="+nub;
        try {
            URL url = new URL(path);
            HttpURLConnection connection = null;
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            int code = connection.getResponseCode();
            if (code == 200) {
                InputStream inputStream = connection.getInputStream();
                json = streamTostring(inputStream, "utf-8");
                Gson gs = new Gson();
                JsonRootBean fromJson = gs.fromJson(json.toString(), JsonRootBean.class);
                newslist = fromJson.getNewslist();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public String streamTostring(InputStream input,String charset) {
        String con = null;
        InputStreamReader inputStreamReader = new InputStreamReader(input);
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(inputStreamReader);
        try {
            while ((con = reader.readLine()) != null) {
                builder.append(con);
            }
            return builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 异步任务
     */
    private void getDataFoamat() {
        AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {
                getDat();
                return null;
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                lvAdapterzt = new LvAdapterzt(Main2.this, newslist);
                lv.setAdapter(lvAdapterzt);
                grAdapter = new GrAdapter(Main2.this, newslist);
                rd.setAdapter(grAdapter);
                mpull.setLayoutMode(MODE_APPEND);
                mpull.setRefreshListener(new BaseRefreshListener() {
                    @Override
                    public void refresh() {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                nub = 15;
                                getDataFoamat();
                                ler.sendEmptyMessageDelayed(0x1,2000);
                            }
                        }).start();
                    }

                    @Override
                    public void loadMore() {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                nub=nub+5;
                                getDataFoamat();
                                ler.sendEmptyMessageDelayed(0x2,2000);
                            }
                        }).start();
                    }
                });

            }
        };
        task.execute();
    }
    private void init() {
        banner = (ConvenientBanner) findViewById(R.id.banner);
        mpull = (PullToRefreshLayout) findViewById(R.id.mpull);
        rd = (GridView) findViewById(R.id.rd);
        lv = (ListView) findViewById(R.id.lv);
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(this));
    }
    private void getinit() {
        banner.setPages(new CBViewHolderCreator<LocalImageNet>() {
            @Override
            public LocalImageNet createHolder() {
                return new LocalImageNet();
            }
        },datalist)
                .setPointViewVisible(true)
                .startTurning(2000)
                .setPageIndicator(new int []{R.drawable.kong,R.drawable.shi})
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                .setManualPageable(true);
    }
    private class LocalImageNet implements Holder<String> {
        @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);
        }
    }
}
接下来是GirdView的适配器:
package com.example.app2_work;

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.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.util.List;

import Bean.Newslist;

/**
 * Created by ZhangTAO on 2017/9/20.
 */

public class GrAdapter extends BaseAdapter{
    Context context;
    List<Newslist> newslist;
    public GrAdapter(Main2 main2, List<Newslist> newslist) {
        this.context = main2;
        this.newslist = newslist;
    }
    @Override
    public int getCount() {
        return newslist.size();
    }
    @Override
    public Object getItem(int i) {
        return newslist.get(i);
    }
    @Override
    public long getItemId(int i) {
        return i;
    }
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View gird = View.inflate(context, R.layout.gird_act, null);
        ImageView img_gr = gird.findViewById(R.id.gr_img);
        TextView tv_gr = gird.findViewById(R.id.gr_title);
        //赋值
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher)
                .build();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .defaultDisplayImageOptions(options).threadPoolSize(5)
                .build();
        ImageLoader.getInstance().init(config);
        ImageLoader.getInstance().displayImage(newslist.get(i).getPicUrl(),img_gr);
        tv_gr.setText(newslist.get(i).getTitle());
        return gird;
    }
}
ListView的适配器代码:
package com.example.app2_work;
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.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import java.util.List;
import Bean.Newslist;
/**
 * Created by ZhangTAO on 2017/9/20.
 */
public class LvAdapterzt extends BaseAdapter{
    Context context;
    List<Newslist> newslist;
    public LvAdapterzt(Main2 main2, List<Newslist> newslist) {
        this.context = main2;
        this.newslist = newslist;
    }
    @Override
    public int getCount() {
        return newslist.size();
    }
    @Override
    public Object getItem(int i) {
        return newslist.get(i);
    }
    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View list = View.inflate(context, R.layout.list_act,null);
        ImageView img_list = list.findViewById(R.id.lv_img);
        TextView tv_list = list.findViewById(R.id.lv_title);
        //赋值
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher)
                .build();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .defaultDisplayImageOptions(options).threadPoolSize(5)
                .build();
        ImageLoader.getInstance().init(config);
        ImageLoader.getInstance().displayImage(newslist.get(i).getPicUrl(),img_list);
        tv_list.setText(newslist.get(i).getTitle());
        return list;
    }
}
第二个页面的图片展示:

第二个页面同样具有上载下拉,只不过是整个页面在上载下拉。
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    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.example.app2_work.MainActivity">

    <android.support.design.widget.AppBarLayout android:layout_width="match_parent"
        android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:background="@color/slect"
            app:popupTheme="@style/AppTheme.PopupOverlay" >
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:id="@+id/rel"
                android:background="@color/slect"
                android:layout_alignParentTop="true"
                >
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/tev"
                    android:text="今日头条"
                    android:textSize="40dp"
                    android:layout_alignParentBottom="true"
                    android:layout_marginBottom="10dp"
                    android:textColor="@color/kong"
                    />
                <EditText
                    android:layout_width="200dp"
                    android:layout_height="30dp"
                    android:id="@+id/et"
                    android:textColor="@color/hei"
                    android:layout_toRightOf="@id/tev"
                    android:layout_alignParentBottom="true"
                    android:layout_marginBottom="18dp"
                    android:layout_marginLeft="45dp"
                    android:hint="淘宝万物"
                    android:background="@color/kong"
                    />
                <Button
                    android:layout_width="60dp"
                    android:layout_height="30dp"
                    android:id="@+id/btn"
                    android:layout_toRightOf="@id/et"
                    android:text="搜索"
                    android:layout_alignParentBottom="true"
                    android:layout_marginBottom="18dp"
                    android:background="@color/hui"
                    />
            </RelativeLayout>
        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />
</android.support.design.widget.CoordinatorLayout>


新手开车,勿喷,谢谢!!!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值