PullToRefresh下拉刷新、上拉加载更多ViewPage+Handler完成无限轮播
例题:
![](https://images2017.cnblogs.com/blog/1292356/201712/1292356-20171220093909990-1251795499.png)
PullToRefresh下拉刷新、上拉加载更多
封装网络请求工具类和网络状态判断工具类,应用打开时,判断网络是否可用,不可用时弹出对话框提示用户进入设置页面,网络正常时弹出吐司,提示网络正常。
使用ViewPage+Handler完成无限轮播效果,轮播图使用Universal-Image-Loader加载网上图片资源(图片链接自己准备),给轮播图里的图片设置点击事件,点击后打开“https://www.baidu.com”
接口 http://120.27.23.105/product/searchProducts?keywords=%E7%AC%94%E8%AE%B0%E6%9C%AC&source=android&page=
=============================================
libs文件夹下加入jar包(导包): gson 和 universal-image-loader
=======================================
build.gradle中加入依赖(加在最下面):
pull-to-refresh上下拉刷新控件 :compile 'com.github.userswlwork:pull-to-refresh:1.0.0'
添加之后需要点击右上角的 Sync Now 编译一下
====================================
添加权限:
网络请求权限:INTERNET
<uses-permission android:name="android.permission.INTERNET"/>
网络判断权限:ACCESS_NETWORK_STATE
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application/>在这个控件里加入属性:android:name=".MyApp"
========================================
MyApp 类
import android.app.Application;
import com.example.shenhuiran_1219_zoukao.utils.ImageLoaderUtils;
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
ImageLoaderUtils.initImageLoader(this);
}
}
====================================================
ImageLoaderUtils 类(工具类)
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import java.io.File;
public class ImageLoaderUtils {
//初使化 context
public static void initImageLoader(Context context){
//自定义
File cachefile=new File(Environment.getExternalStorageDirectory().getPath()+"/image");
ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(context)
.memoryCacheExtraOptions(480, 800)//缓存图片最大的长和宽
.threadPoolSize(2)//线程池的数量
.threadPriority(4)
.memoryCacheSize(20*1024*1024)//设置内存缓存区大小
.diskCacheSize(20*1024*1024)//设置sd卡缓存区大小
.diskCache(new UnlimitedDiscCache(cachefile))//自定义缓存目录
.writeDebugLogs()//打印日志内容
.diskCacheFileNameGenerator(new Md5FileNameGenerator())//给缓存的文件名进行md5加密处理
.build();
ImageLoader.getInstance().init(configuration);
}
//得到显示图片设置类
public static DisplayImageOptions getImageOptions(Context context){
DisplayImageOptions options=new DisplayImageOptions.Builder()
.cacheInMemory(true)//使用内存缓存
.cacheOnDisk(true)//使用磁盘缓存
.bitmapConfig(Bitmap.Config.RGB_565)//设置图片色彩模式
.imageScaleType(ImageScaleType.EXACTLY)//设置图片的缩放模式
.build();
return options;
}
}
===========================================================
Result方法:
public class Result {
json解析类 }
===================================================
布局:
<com.handmark.pulltorefresh.library.PullToRefreshScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.shenhuiran_1219_zoukao.MainActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/psv">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="@+id/vp"></android.support.v4.view.ViewPager>
<com.example.shenhuiran_1219_zoukao.MyListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lv"></com.example.shenhuiran_1219_zoukao.MyListView>
</LinearLayout>
</com.handmark.pulltorefresh.library.PullToRefreshScrollView>
------------------------------------------------------------------
MyListView 类
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class MyListView extends ListView {
public MyListView(Context context) {
super(context);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int newheight=MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, newheight);
}
}
===================================================================
主要代码:
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Toast;
import com.example.shenhuiran_1219_zoukao.utils.MyTask;
import com.example.shenhuiran_1219_zoukao.utils.NetUtils;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private PullToRefreshScrollView psv;
private ViewPager viewPager;
private ListView listView;
private int pageIndex=1;
private int operType=1;
private String url="http://120.27.23.105/product/searchProducts?keywords=%E7%AC%94%E8%AE%B0%E6%9C%AC&source=android&page="+pageIndex;
private List<Result.DataBean> data=new ArrayList<>();
private List<String> picUrl;
private MyAdapter adapter;
private Handler myHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int index=viewPager.getCurrentItem();
index++;
viewPager.setCurrentItem(index);
sendEmptyMessageDelayed(0,500);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
picUrl=new ArrayList<>();
psv = findViewById(R.id.psv);
viewPager = findViewById(R.id.vp);
listView = findViewById(R.id.lv);
initPsv();
initData();
if(NetUtils.isConn(this)){//有网络
Toast.makeText(this,"有网络",Toast.LENGTH_SHORT).show();
//设置适配器
viewPager.setAdapter(new MyPagerAdapter(this,picUrl));
//设置默认显示页面
viewPager.setCurrentItem(picUrl.size()*10);
//发消息
myHandler.sendEmptyMessage(0);
requestNetData();
}else {
NetUtils.openDg(this);
}
}
//请求网络数据
private void requestNetData() {
MyTask myTask=new MyTask(new MyTask.Icallback() {
@Override
public void getJsonData(String json) {
Gson gson=new Gson();
Result result = gson.fromJson(json, Result.class);
if(operType==1){
data.clear();//刷新时,清空数据集合
}
data.addAll(result.getData());
setAdapter();
//关闭头尾布局
psv.onRefreshComplete();
}
});
myTask.execute(url);
}
public void setAdapter(){
if(adapter==null){
adapter=new MyAdapter(this,data);
listView.setAdapter(adapter);
}else {
adapter.notifyDataSetChanged();
}
}
private void initData() {
picUrl.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1513679323820&di=d33523977cd2b8c0e831513baa205965&imgtype=0&src=http%3A%2F%2Fc.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2Fa686c9177f3e67092b94a19231c79f3df9dc55c3.jpg");
picUrl.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1513679323820&di=9d535a4011922065fc36e1d0cb3790fa&imgtype=0&src=http%3A%2F%2Fb.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2Fac4bd11373f082024ba9705241fbfbedab641ba7.jpg");
picUrl.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1513679323820&di=7d77f15e8f8556eb72fee9b0962ef985&imgtype=0&src=http%3A%2F%2Ff.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2Fc75c10385343fbf25fb0ff46ba7eca8065388f33.jpg");
}
private void initPsv() {
psv.setMode(PullToRefreshBase.Mode.BOTH);
psv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ScrollView> pullToRefreshBase) {
pageIndex=1;
url="http://120.27.23.105/product/searchProducts?keywords=%E7%AC%94%E8%AE%B0%E6%9C%AC&source=android&page="+pageIndex;
operType=1;
requestNetData();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ScrollView> pullToRefreshBase) {
//加载更多
pageIndex++;
url="http://120.27.23.105/product/searchProducts?keywords=%E7%AC%94%E8%AE%B0%E6%9C%AC&source=android&page="+pageIndex;
operType=2;
requestNetData();
}
});
}
}
============================================================
NetUtils 类(工具类)
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;
import com.example.shenhuiran_1219_zoukao.R;
public class NetUtils {
public static boolean isConn(Context context){
boolean result=true;
ConnectivityManager manager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if(networkInfo!=null && networkInfo.isAvailable()){
result=true;
}else {
result=false;
}
return result;
}
public static void openDg(final Context context){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(R.mipmap.ic_launcher) //
.setTitle(R.string.app_name) //
.setMessage("当前无网络").setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 跳转到系统的网络设置界面
Intent intent = null;
// 先判断当前系统版本
if(android.os.Build.VERSION.SDK_INT > 10){ // 3.0以上
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
}else{
intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");
}
context.startActivity(intent);
}
}).setNegativeButton("知道了", null).show();
}
}
=================================================
MyTask 类(工具类)
import android.os.AsyncTask;
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;
public class MyTask extends AsyncTask<String,Void,String> {
private Icallback icallback;
public MyTask(Icallback icallback) {
this.icallback = icallback;
}
@Override
protected String doInBackground(String... strings) {
StringBuilder builder=new StringBuilder();
try {
URL url=new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
if(connection.getResponseCode()==200){
InputStream inputStream = connection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
String str;
while ((str=reader.readLine())!=null){
builder.append(str);
}
return builder.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
icallback.getJsonData(s);
}
//定义一个接口
public interface Icallback{
void getJsonData(String json);
}
}
=========================================
MyAdapter 类(适配器)
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.example.shenhuiran_1219_zoukao.utils.ImageLoaderUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.List;
public class MyAdapter extends BaseAdapter {
private Context context;
private List<Result.DataBean> data;
public MyAdapter(Context context, List<Result.DataBean> data) {
this.context = context;
this.data = data;
}
@Override
public int getCount() {
return data.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(context,R.layout.item,null);
holder=new ViewHolder();
holder.imageView=view.findViewById(R.id.img);
holder.tvTitle=view.findViewById(R.id.tv_title);
holder.tvPrice=view.findViewById(R.id.tv_price);
view.setTag(holder);
}else {
holder=(ViewHolder) view.getTag();
}
holder.tvTitle.setText(data.get(i).getTitle());
holder.tvPrice.setText("¥"+data.get(i).getPrice());
ImageLoader.getInstance().displayImage(data.get(i).getImages(),holder.imageView, ImageLoaderUtils.getImageOptions(context));
return view;
}
class ViewHolder{
ImageView imageView;
TextView tvTitle;
TextView tvPrice;
}
}
-------------------------------------------------
R.layout.item
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="@+id/img"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_title"
android:layout_toRightOf="@+id/img"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_price"
android:layout_toRightOf="@+id/img"
android:layout_below="@+id/tv_title"/>
</RelativeLayout>
========================================================
MyPagerAdapter 类
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.shenhuiran_1219_zoukao.utils.ImageLoaderUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.List;
public class MyPagerAdapter extends PagerAdapter {
private Context context;
private List<String> urls;
public MyPagerAdapter(Context context, List<String> urls) {
this.context = context;
this.urls = urls;
}
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView=new ImageView(context);
//加载显示图片
ImageLoader.getInstance().displayImage(urls.get(position%urls.size()),imageView, ImageLoaderUtils.getImageOptions(context));
//添加进去
container.addView(imageView);
//添加点击事件
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(context,Main2Activity.class);
intent.putExtra("key","http://baidu.com");
context.startActivity(intent);
}
});
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
=====================================================
Main2Activity类(点击跳转网页)
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
String url = intent.getStringExtra("key");
WebView webView=findViewById(R.id.wv);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
//在本工程中显示网页,不去调用 系统浏览器
webView.setWebViewClient(new WebViewClient());
//加载网页
webView.loadUrl(url);
}
}
---------------------------------------
布局:R.layout.activity_main2
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.shenhuiran_1219_zoukao.Main2Activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/wv"></WebView>
</android.support.constraint.ConstraintLayout>