import android.os.AsyncTask;
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.view.View;
import android.widget.Toast;

import com.bawei.jane.mxlistview.view.XListView;
import com.example.weekend_03.utils.NetUtils;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {
private List picUrl;
private XListView xlv;
private int pageIndex=1;//第一页的数据
private String urlpart="http://www.93.gov.cn/93app/data.do?channelId=0&startNum=";

private String url =urlpart + pageIndex;

private MyAdapter adapter;
private List data = new ArrayList();
private int operType = 1;
private ViewPager viewpage;

private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int index = viewpage.getCurrentItem();
index++;
viewpage.setCurrentItem(index);
sendEmptyMessageDelayed(0,500);
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
picUrl = new ArrayList();
xlv = findViewById(R.id.xlv);
viewpage = findViewById(R.id.vp);

if (NetUtils.isConn(this)){
initData();
MyTask myTask = new MyTask();
myTask.execute(url);

Toast.makeText(this,"有网络",Toast.LENGTH_SHORT).show();
//设置适配器
viewpage.setAdapter(new MyPagerAdapter(picUrl,this));
//设置默认显示页面
viewpage.setCurrentItem(picUrl.size()*10);
//发消息
handler.sendEmptyMessage(0);

}else{
NetUtils.openDg(this);
}
xlv.setPullRefreshEnable(true);
xlv.setPullLoadEnable(true);
xlv.setXListViewListener(new XListView.IXListViewListener() {
@Override
public void onRefresh() {

pageIndex = 1;
url = urlpart+pageIndex;
//重新赋值
operType=1;
MyTask myTask = new MyTask();
myTask.execute(url);

}

@Override
public void onLoadMore() {
// 页数增加
pageIndex++;
url=urlpart+pageIndex;
// 重新赋值
operType =2;
MyTask task = new MyTask();
task.execute(url);

}
});

}

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");
}

class MyTask extends AsyncTask {
@Override
protected String doInBackground(String... strings) {
StringBuilder builder = new StringBuilder();
try {
URL url = new URL(strings[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setReadTimeout(5000);
c.setConnectTimeout(5000);
if (c.getResponseCode()==200){
InputStream inputStream = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String str;
while ((str=reader.readLine())!=null){
builder.append(str);
}
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return builder.toString();
}

@Override
protected void onPostExecute(String s) {
Gson gson = new Gson();
Result result = gson.fromJson(s, Result.class);

if (operType==1){
data.clear();
}
data.addAll(result.getData());
setAdapter();
//关闭头尾布局
if (operType ==1){
xlv.stopRefresh();
Date date = new Date(System.currentTimeMillis());//获取当前时间
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化时间
String refreShTime = sf.format(date);
xlv.setRefreshTime(refreShTime);//设置刷新时间
}else {
xlv.stopLoadMore();//关闭尾布局

}

}
}
public void setAdapter(){
if (adapter==null){
adapter = new MyAdapter(data,MainActivity.this);
xlv.setAdapter(adapter);
}else {
adapter.notifyDataSetChanged();
}
}
}

==================================================================================工具类

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;

/**
* Created by jane on 2017/12/19.
*/

public class ImageLoaderUtils {

/**
* 初使化
* @param 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);

}

/**
* 得到显示图片设置类
* @param context
* @return
*/
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;
}
}

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

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.weekend_03.R;

/**
* Created by jane on 2017/12/19.
*/

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();

}
}

=====================================================================================

import android.app.Application;

/**
* Created by jane on 2017/12/19.
*/

public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
ImageLoaderUtils.initImageLoader(this);
}
}

====================================================================================================

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.weekend_03.utils.ImageLoaderUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.List;

/**
* Created by lenovo on 2017/12/19.
*/

class MyPagerAdapter extends PagerAdapter {
private Listurls;
private Context context;

public MyPagerAdapter(List urls, Context context) {
this.urls = urls;
this.context = context;
}

@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://www.baidu.com");
context.startActivity(intent);
}
});
return imageView;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {

container.removeView((View) object);
}
}

====================================================================================================

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.weekend_03.utils.ImageLoaderUtils;
import com.google.gson.Gson;
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.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
* Created by lenovo on 2017/12/19.
*/

class MyAdapter extends BaseAdapter{
private Listlist;
private Context context;
public MyAdapter(List list, Context context) {
this.list = list;
this.context = context;
}
//定义了两个常量,注意定义的常量值一定要小于 类型的总数 (2)
private final int HAS_IMAGE=0;//有图
private final int NO_IMAGE=1;//无图

//得到item条目的类型总数
@Override
public int getViewTypeCount() {
return 2;
}

//根据条目的下标,返回此条目对应的类型,返回值是int类型
//position:item的索引值,下标
@Override
public int getItemViewType(int position) {
if(list.get(position).getIMAGEURL()==null){//偶数,返回无图类型
return NO_IMAGE;
}else{
return HAS_IMAGE;
}
}

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

@Override
public Object getItem(int i) {
return list.get(i);
}

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

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

if (getItemViewType(i)==HAS_IMAGE){
view = View.inflate(context,R.layout.itme,null);
TextView title = view.findViewById(R.id.title);
ImageView img = view.findViewById(R.id.img);

title.setText(list.get(i).getTITLE());
Log.d("zzz",list.get(i).getIMAGEURL());
ImageLoader.getInstance().displayImage(list.get(i).getIMAGEURL(),img, ImageLoaderUtils.getImageOptions(context));

}else{
view = View.inflate(context,R.layout.itme_1,null);
TextView text1 = view.findViewById(R.id.text1);
text1.setText(list.get(i).getTITLE());

}

return view;
}

}

==============================================================================================

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 {

private WebView webView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
String url = intent.getStringExtra("key");

webView = findViewById(R.id.wv);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
//在本工程中显示网页,不去调用 系统浏览器
webView.setWebViewClient(new WebViewClient());
//加载网页
webView.loadUrl(url);
}
}

=========================================================================================================

ViewpagerHandler的更多相关文章

  1. Android首页轮播图直接拿来用

    import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import jav ...

随机推荐

  1. Wireshark解析MQTT

    Mac下安装lua curl -R -O http://www.lua.org/ftp/lua-5.2.3.tar.gz tar zxf lua-5.2.3.tar.gz cd lua-5.2.3 m ...

  2. Python入门 序列章

    内置函数range range([start,] stop[, step]) 第一个参数表示步长(默认为0),第二个参数表示终止值(结果中不包括这个值),第三个参数表示步长(默认为1, 实验发现不能用 ...

  3. oracle的存储过程的作用

    oracle的存储过程的作用 1.存储过程可以使得程序执行效率更高.安全性更好,因为过程建立之后 已经编译并且储存到数据库,直接写sql就需要先分析再执行因此过程效率更高,直接写sql语句会带来安全性 ...

  4. [Hibernate] 分页查询

    @Test public void test9(){ //根据部门编号进行分组,再根据每个部门总工资>5000 Session ss=HibernateUtil.getSession(); St ...

  5. RabbitMQ(3) Spring boot集成RabbitMQ

    springboot集成RabbitMQ非常简单,如果只是简单的使用配置非常少,springboot提供了spring-boot-starter-amqp项目对消息各种支持. 资源代码:练习用的代码. ...

  6. LeetCode--017--电话号码的字母组合(java)

    给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合. 给出数字到字母的映射如下(与电话按键相同).注意 1 不对应任何字母. 示例: 输入:"23" 输出:[&quo ...

  7. liunx存储管理之基础知识

    存储基础知识 ====================================================================================主要知识点: 基本 ...

  8. MySQL三层循环

    begindeclare i int;  #定义i变量declare j int;  #定义j变量declare k int;  #定义k变量set i=1;set j=1;set k=1;while ...

  9. protobuf example make backup

    # See README.txt. .PHONY: all cpp java python clean all: cpp #java python cpp: add_person_cpp list_p ...

  10. layer中每次用到都要查来查去的功能

    1.关闭当前弹出层 var index = parent.layer.getFrameIndex(window.name); setTimeout(function(){parent.layer.cl ...