无限轮播图+pulltorefresh+侧滑

来源:互联网 发布:菜鸟网络 工作强度 编辑:程序博客网 时间:2024/06/01 09:29

drawable/select.xml

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android">    <solid android:color="#0af" />    <corners android:radius="5dp" />    <size        android:width="10dp"        android:height="10dp" /></shape>

drawable/select_no.xml

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android">    <solid android:color="#000" />    <corners android:radius="5dp" />    <size        android:width="10dp"        android:height="10dp" /></shape>


activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent">    <android.support.v4.view.ViewPager        android:id="@+id/vp"        android:layout_width="match_parent"        android:layout_height="match_parent"></android.support.v4.view.ViewPager>    <Button        android:id="@+id/jrxt"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:layout_alignParentRight="true"        android:text="进入系统" />    <LinearLayout        android:id="@+id/line"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBottom="@+id/vp"        android:layout_centerHorizontal="true"        android:layout_marginBottom="20dp"        android:orientation="horizontal"></LinearLayout></RelativeLayout>

main2.xml

<?xml version="1.0" encoding="utf-8"?><android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="vertical">        <com.handmark.pulltorefresh.library.PullToRefreshListView xmlns:ptr="http://schemas.android.com/apk/res-auto"            android:id="@+id/refresh_list_view"            android:layout_width="match_parent"            android:layout_height="match_parent"            ptr:ptrAnimationStyle="flip"            ptr:ptrDrawable="@drawable/default_ptr_flip"            ptr:ptrHeaderBackground="#383838"            ptr:ptrHeaderTextColor="#FFFFFF" />    </LinearLayout>    <LinearLayout        android:id="@+id/line"        android:layout_width="200dp"        android:layout_height="match_parent"        android:layout_gravity="start"        android:background="#000"        android:orientation="vertical">        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="horizontal">            <ImageView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:src="@mipmap/ic_launcher" />            <ImageView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:src="@mipmap/ic_launcher" />            <ImageView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:src="@mipmap/ic_launcher" />        </LinearLayout>        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="关闭侧滑栏"            android:textColor="#fff"            android:textSize="40dp" />        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="关闭侧滑栏"            android:textColor="#fff"            android:textSize="40dp" />        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="关闭侧滑栏"            android:textColor="#fff"            android:textSize="40dp" />    </LinearLayout></android.support.v4.widget.DrawerLayout>


MainActivity

import android.content.Intent;import android.os.AsyncTask;import android.os.Handler;import android.os.Message;import android.support.v4.view.PagerAdapter;import android.support.v4.view.ViewPager;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.MotionEvent;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.ImageView;import android.widget.LinearLayout;import com.google.gson.Gson;import com.nostra13.universalimageloader.core.ImageLoader;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity {    private ViewPager vp;    private List<Bean.ResultBean.DataBean> list;    private List<ImageView> data = new ArrayList<>();    private String path = "http://apis.juhe.cn/cook/query?key=ab2da3f9abd4556dfd68086a66ffc4a8&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF&rn=10&pn=3";    private Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            if (msg.what == 0) {                int currentItem = vp.getCurrentItem();                vp.setCurrentItem(currentItem + 1);                handler.sendEmptyMessageDelayed(0, 2000);            }        }    };    private LinearLayout line;    private List<ImageView> imageViews;    private Button jrxt;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        vp = (ViewPager) findViewById(R.id.vp);        line = (LinearLayout) findViewById(R.id.line);        jrxt = (Button) findViewById(R.id.jrxt);        jrxt.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Intent intent = new Intent(MainActivity.this, Main2.class);                startActivity(intent);            }        });        new My().execute();    }    class My extends AsyncTask {        @Override        protected Object doInBackground(Object[] objects) {            String string = "";            try {                URL url = new URL(path);                HttpURLConnection con = (HttpURLConnection) url.openConnection();                int code = con.getResponseCode();                if (code == 200) {                    InputStream is = con.getInputStream();                    byte[] b = new byte[1024];                    int l = 0;                    while ((l = is.read(b)) != -1) {                        String str = new String(b, 0, l);                        string += str;                    }                }            } catch (Exception e) {                e.printStackTrace();            }            return string;        }        @Override        protected void onPostExecute(Object o) {            super.onPostExecute(o);            Gson gson = new Gson();            list = gson.fromJson((String) o, Bean.class).getResult().getData();            for (int i = 0; i < list.size(); i++) {                ImageView imageView = new ImageView(MainActivity.this);                ImageLoader.getInstance().displayImage(list.get(i).getAlbums().get(0), imageView);                data.add(imageView);            }            initDoc();            ImgAdapter imgAdapter = new ImgAdapter();            vp.setAdapter(imgAdapter);            vp.setCurrentItem(data.size() * 10000);            handler.sendEmptyMessageDelayed(0, 2000);            vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {                @Override                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {                }                @Override                public void onPageSelected(int position) {                    for (int i = 0; i < imageViews.size(); i++) {                        if (i == position % imageViews.size()) {                            imageViews.get(i).setImageResource(R.drawable.select);                        } else {                            imageViews.get(i).setImageResource(R.drawable.select_no);                        }                    }                }                @Override                public void onPageScrollStateChanged(int state) {                }            });        }    }    private void initDoc() {        imageViews = new ArrayList<>();        line.removeAllViews();        for (int i = 0; i < list.size(); i++) {            ImageView imageView = new ImageView(MainActivity.this);            if (i == 0) {                imageView.setImageResource(R.drawable.select);            } else {                imageView.setImageResource(R.drawable.select_no);            }            imageViews.add(imageView);            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);            params.setMargins(5, 0, 5, 0);            line.addView(imageView, params);        }    }    class ImgAdapter extends PagerAdapter {        @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 = data.get(position % data.size());            imageView.setOnTouchListener(new View.OnTouchListener() {                @Override                public boolean onTouch(View view, MotionEvent motionEvent) {                    boolean isTZ = true;                    switch (motionEvent.getAction()) {                        case MotionEvent.ACTION_DOWN://按下                            handler.removeCallbacksAndMessages(null);                            break;                        case MotionEvent.ACTION_MOVE://移动                            isTZ = false;                            handler.removeCallbacksAndMessages(null);                            break;                        case MotionEvent.ACTION_CANCEL://取消                            isTZ = false;                            handler.sendEmptyMessageDelayed(0, 2000);                            break;                        case MotionEvent.ACTION_UP://抬起                            handler.sendEmptyMessageDelayed(0, 2000);                            break;                    }                    return true;                }            });            container.addView(imageView);            return imageView;        }        @Override        public void destroyItem(ViewGroup container, int position, Object object) {            container.removeView((View) object);        }    }}

Main2

import android.os.AsyncTask;import android.os.Bundle;import android.support.v4.widget.DrawerLayout;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.ListView;import android.widget.TextView;import com.google.gson.Gson;import com.handmark.pulltorefresh.library.ILoadingLayout;import com.handmark.pulltorefresh.library.PullToRefreshBase;import com.handmark.pulltorefresh.library.PullToRefreshListView;import com.nostra13.universalimageloader.core.ImageLoader;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.List;public class Main2 extends AppCompatActivity {    private PullToRefreshListView refreshListView;    private MyAdapter adapter;    private ILoadingLayout startLabels;    private ILoadingLayout endLabels;    private int page = 10;    private List<Bean.ResultBean.DataBean> data;    private DrawerLayout drawerLayout;    private LinearLayout line;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main2);        refreshListView = (PullToRefreshListView) findViewById(R.id.refresh_list_view);        drawerLayout = (DrawerLayout) findViewById(R.id.activity_main);        line = (LinearLayout) findViewById(R.id.line);        //获取数据,,,设置适配器        new My().execute();        //设置刷新时显示的刷新状态        /**设置pullToRefreshListView的刷新模式,BOTH代表支持上拉和下拉,         PULL_FROM_END代表上拉,PULL_FROM_START代表下拉 */        refreshListView.setMode(PullToRefreshBase.Mode.BOTH);        /**         * 设置下拉和上拉的时候显示的文字         */        //通过getLoadingLayoutProxy 方法来指定上拉和下拉时显示的文字的区别,第一个true 代表下来状态 ,第二个true 代表上拉的状态        startLabels = refreshListView.getLoadingLayoutProxy(true, false);        startLabels.setPullLabel("下拉刷新");        startLabels.setRefreshingLabel("正在刷新...");        startLabels.setReleaseLabel("放开刷新");        endLabels = refreshListView.getLoadingLayoutProxy(false, true);        endLabels.setPullLabel("上拉刷新");        endLabels.setRefreshingLabel("正在载入...");        endLabels.setReleaseLabel("放开刷新...");        //设置上拉下拉的监听事件        /**         * 当然也可以设置为OnRefreshListener2,但是Mode.PULL_FROM_START的时候只         * 调用onPullDownToRefresh()方法,         * Mode.PULL_FROM_END的时候只调用onPullUpToRefresh()方法.         */        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {            //下拉的时候调用            @Override            public void onPullDownToRefresh(final PullToRefreshBase<ListView> refreshView) {                //加载数据(异步的操作)....数据完成之后,取消刷新                //执行onRefreshComplete();方法必须在异步下执行,不能和主进程一起执行                page--;                new My().execute();            }            //上拉的时候调用            @Override            public void onPullUpToRefresh(final PullToRefreshBase<ListView> refreshView) {                page++;                new My().execute();            }        });    }    class My extends AsyncTask {        @Override        protected Object doInBackground(Object[] objects) {            String string = "";            String path = "http://apis.juhe.cn/cook/query?key=ab2da3f9abd4556dfd68086a66ffc4a8&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF&rn=10&pn=" + page;            try {                URL url = new URL(path);                HttpURLConnection con = (HttpURLConnection) url.openConnection();                int code = con.getResponseCode();                if (code == 200) {                    InputStream is = con.getInputStream();                    byte[] b = new byte[1024];                    int l = 0;                    while ((l = is.read(b)) != -1) {                        String str = new String(b, 0, l);                        string += str;                    }                }            } catch (Exception e) {                e.printStackTrace();            }            return string;        }        @Override        protected void onPostExecute(Object o) {            super.onPostExecute(o);            Gson gson = new Gson();            Bean bean = gson.fromJson((String) o, Bean.class);            data = bean.getResult().getData();            if (adapter == null) {                adapter = new MyAdapter();                refreshListView.setAdapter(adapter);            } else {                adapter.notifyDataSetChanged();            }            refreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {                @Override                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {                    drawerLayout.openDrawer(line);                }            });            refreshListView.onRefreshComplete();        }    }    class MyAdapter extends BaseAdapter {        @Override        public int getCount() {            return data.size();        }        @Override        public Object getItem(int i) {            return data.get(i);        }        @Override        public long getItemId(int i) {            return i                    ;        }        @Override        public View getView(int i, View view, ViewGroup viewGroup) {            Hand hand;            if (view == null) {                view = View.inflate(Main2.this, R.layout.item, null);                hand = new Hand();                hand.te1 = view.findViewById(R.id.te1);                hand.te2 = view.findViewById(R.id.te2);                hand.te3 = view.findViewById(R.id.te3);                hand.img = view.findViewById(R.id.img);                view.setTag(hand);            } else {                hand = (Hand) view.getTag();            }            hand.te1.setText(data.get(i).getTitle());            hand.te2.setText(data.get(i).getIngredients());            hand.te3.setText(data.get(i).getBurden());            String url = data.get(i).getAlbums().get(0);            ImageLoader il = ImageLoader.getInstance();            il.displayImage(url, hand.img);            return view;        }    }    class Hand {        ImageView img;        TextView te1, te2, te3;    }}



ImageLoaderUtil

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.HashCodeFileNameGenerator;import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;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 com.nostra13.universalimageloader.core.assist.QueueProcessingType;import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;import com.nostra13.universalimageloader.core.download.BaseImageDownloader;import java.io.File;/** * @author Dash * @date 2017/9/11 * @description: */public class ImageLoaderUtil {    /**     * 配置的方法     * @param context     */    public static void initConfig(Context context) {        File cacheDir = new File(Environment.getExternalStorageDirectory(),"/image");  //缓存文件夹路径        if (!cacheDir.exists()){            cacheDir.mkdirs();        }        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)                .threadPoolSize(3)                .threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级                .tasksProcessingOrder(QueueProcessingType.FIFO) // default                .denyCacheImageMultipleSizesInMemory()                .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通过自己的内存缓存实现                .memoryCacheSize(2 * 1024 * 1024)  // 内存缓存的最大值                .memoryCacheSizePercentage(13) // default                .diskCache(new UnlimitedDiscCache(cacheDir)) // default 可以自定义缓存路径               // .diskCache(new UnlimitedDiskCache(cacheDir)) // default 可以自定义缓存路径                .diskCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值                .diskCacheFileCount(100)  // 可以缓存的文件数量                // default为使用HASHCODE对UIL进行加密命名, 还可以用MD5(new Md5FileNameGenerator())加密                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator())                .imageDownloader(new BaseImageDownloader(context)) // default                .imageDecoder(new BaseImageDecoder(true)) // default                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default                .writeDebugLogs() // 打印debug log                .build(); //开始构建        ImageLoader.getInstance().init(config);    }    public static DisplayImageOptions getOption() {        DisplayImageOptions options = new DisplayImageOptions.Builder()                .showImageOnLoading(R.mipmap.ic_launcher) // 设置图片下载期间显示的图片                .showImageForEmptyUri(R.mipmap.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片                .showImageOnFail(R.mipmap.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片                .resetViewBeforeLoading(true)  // default 设置图片在加载前是否重置、复位                .delayBeforeLoading(1000)  // 下载前的延迟时间                .cacheInMemory(true) // default  设置下载的图片是否缓存在内存中                .cacheOnDisk(true) // default  设置下载的图片是否缓存在SD卡中                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED) // default 设置图片以如何的编码方式显示                .bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型                .build();        return options;    }}


Myapp

import android.app.Application;/** * Created by lenovo on 2017/09/19. */public class Myapp extends Application{    @Override    public void onCreate() {        super.onCreate();        ImageLoaderUtil.initConfig(this);    }}




<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="fragment.bwie.com.lx0919">    <uses-permission android:name="android.permission.INTERNET" />    <application        android:name=".Myapp"        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name=".Main2"/>    </application></manifest>