码迷,mamicode.com
首页 > 其他好文 > 详细

图片无限轮播加上下拉刷新

时间:2018-04-26 23:38:47      阅读:622      评论:0      收藏:0      [点我收藏+]

标签:lists   type   let   disk   lse   index   messages   长度   puts   

 

public class Second extends Activity{

    private int pageIndex=1;

    private int operType=1;

    private String myurl="http://365jia.cn/news/api3/365jia/news/headline?page="+pageIndex;

 

    private List<String> imgUrls=new ArrayList<>();

    private List<Urse.DataBeanX.DataBean> datas=new ArrayList<>();

    private PullToRefreshScrollView psv;

    private ListView listView;

    private ViewPager vp;

    private LinearLayout linPoint;

    private ListViewAdapter adapter;

    private List<ImageView> lists=new ArrayList<>();

 

 

    @SuppressLint("HandlerLeak")

    private Handler mhandler =new Handler(){

        @Override

        public void handleMessage(Message msg) {

            super.handleMessage(msg);

 

            int cIndex = vp.getCurrentItem();

            cIndex++;

            vp.setCurrentItem(cIndex);

 

            setSelectedPoint(cIndex%lists.size());

 

            sendEmptyMessageDelayed(0,1000);

        }

    };

 

 

    @Override

    public void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main2);

        psv = findViewById(R.id.psv);

        listView = findViewById(R.id.lv);

        vp = findViewById(R.id.vp);

        linPoint = findViewById(R.id.lin_point);

//初始化

        initPsv();

//请求数据

        recreatData();

 

    }

 

    private void recreatData() {

        new MyTask().execute(myurl);

    }

 

    public void setSelectedPoint(int pageIndex) {

        for (int i = 0; i <lists.size() ; i++) {

            if (i==pageIndex){

                lists.get(i).setImageResource(R.drawable.point_selected);

            }else {

                lists.get(i).setImageResource(R.drawable.point_unselected);

            }

        }

    }

 

 

    private class MyTask extends AsyncTask<String, Void, String> {

        //在后台执行的任务

        @Override

        protected String doInBackground(String... strings) {//String... 可变长的字符串  string类型的数组,长度不固定

            try {

                URL url = new URL(strings[0]);

                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                InputStream inputStream = urlConnection.getInputStream();

                String s = streamToString(inputStream);

 

                return s;

            } catch (Exception e) {

                e.printStackTrace();

            }

 

 

            return "123";

        }

 

        //在doInBackground之后,调用的方法,,,更新UI的操作,相当于handlerMessage中的功能

        @Override

        protected void onPostExecute(String s) {

            super.onPostExecute(s);

            //解析+展示

            Gson gson = new Gson();

 

            Urse urse = gson.fromJson(s, Urse.class);

            List<Urse.DataBeanX.DataBean> data = urse.getData().getData();

 

            showPics(data);

 

           

            if (operType == 1) {

                datas.clear();

            }

            datas.addAll(data);

 

            setAdapter();

 

            psv.onRefreshComplete();

        }

    }

    private void showPics(List<Urse.DataBeanX.DataBean> data) {

        imgUrls.clear();

        imgUrls.add("http://365jia.cn/uploads/"+data.get(0).getPics().get(0));

        imgUrls.add("http://365jia.cn/uploads/"+data.get(1).getPics().get(0));

        imgUrls.add("http://365jia.cn/uploads/"+data.get(2).getPics().get(0));

 

        MyAdapter adapter = new MyAdapter(imgUrls,Second.this);

        vp.setAdapter(adapter);

 

        

        initPoint();

        //Handler发消息

        mhandler.sendEmptyMessageDelayed(0,1000);

    }

 

    private void initPoint() {

        linPoint.removeAllViews();

        lists.clear();

        for (int i = 0; i <imgUrls.size() ; i++) {

            ImageView imageView = new ImageView(this);

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

 

            params.setMargins(0,0,10,0);

            if (i==0){

                imageView.setImageResource(R.drawable.point_selected);

            }else {

                imageView.setImageResource(R.drawable.point_unselected);

            }

            linPoint.addView(imageView,params);

            lists.add(imageView);

 

            }

        }

 

 

 

    private void setAdapter() {

        if (adapter==null) {

            adapter = new ListViewAdapter(datas,Second.this);

            listView.setAdapter(adapter);

        }else {

            adapter.notifyDataSetChanged();

        }

    }

 

    private String streamToString(InputStream stream) {

        StringBuilder builder = new StringBuilder();

        String str;

        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

        try {

            while ((str=reader.readLine())!=null){

                builder.append(str);

                Log.i("jljs", builder.toString());

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

        return  builder.toString();

    }

 

 

 

    private void initPsv() {

        psv.setMode(PullToRefreshBase.Mode.BOTH);

 

        psv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {

            @Override

            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> pullToRefreshBase) {

                //刷新回调

                operType=1;

                pageIndex=1;

                myurl="http://365jia.cn/news/api3/365jia/news/headline?page="+pageIndex;

                mhandler.removeCallbacksAndMessages(null);

                recreatData();

 

            }

 

            @Override

            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> pullToRefreshBase) {

                //加载回调

                operType=2;

                pageIndex++;

                myurl="http://365jia.cn/news/api3/365jia/news/headline?page="+pageIndex;

                mhandler.removeCallbacksAndMessages(null);

                recreatData();

            }

        });

    }

}

 

 

 

class MyAdapter extends PagerAdapter {

 

    //数据源

    private List<String> urls;

    //上下文对象

    private Context context;

 

    private DisplayImageOptions options;

 

    public MyAdapter(List<String> urls, Context context) {

        this.urls = urls;

        this.context = context;

        this.options=new DisplayImageOptions.Builder()

                .cacheInMemory(true)//使用内存缓存

                .cacheOnDisk(true)//使用磁盘缓存

                .showImageOnLoading(R.mipmap.ic_launcher)//设置正在下载的图片

                .showImageForEmptyUri(R.mipmap.ic_launcher)//url为空或请求的资源不存在时

                .showImageOnFail(R.mipmap.ic_launcher)//下载失败时显示的图片

                .bitmapConfig(Bitmap.Config.RGB_565)//设置图片色彩模式  1px=2个字节  ARGB_8888 1px=4个字节   ARGB_4444 1px=2个字节  ALPHA_8 1px=1个字节

                .imageScaleType(ImageScaleType.EXACTLY)//设置图片的缩放模式

                .build();

    }

 

    @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,options);

 

        container.addView(imageView);

        return imageView;

    }

 

    @Override

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

        //super.destroyItem(container, position, object);

        container.removeView((View)object);

    }

}

 

 

 

class ListViewAdapter extends BaseAdapter {

 

    private List<Urse.DataBeanX.DataBean> data;

    private Context context;

    private final DisplayImageOptions options;

 

    public ListViewAdapter( List<Urse.DataBeanX.DataBean> data, Context context) {

        this.data = data;

        this.context = context;

 

        options = new DisplayImageOptions.Builder()

                .cacheInMemory(true)//使用内存缓存

                .cacheOnDisk(true)//使用磁盘缓存

                .showImageOnLoading(R.mipmap.ic_launcher)//设置正在下载的图片

                .showImageForEmptyUri(R.mipmap.ic_launcher)//url为空或请求的资源不存在时

                .showImageOnFail(R.mipmap.ic_launcher)//下载失败时显示的图片

                .bitmapConfig(Bitmap.Config.RGB_565)//设置图片色彩模式  1px=2个字节  ARGB_8888 1px=4个字节   ARGB_4444 1px=2个字节  ALPHA_8 1px=1个字节

                .imageScaleType(ImageScaleType.EXACTLY)//设置图片的缩放模式

                .build();

    }

 

 

 

 

    @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) {

        ViewHolder holder;

        if(view==null){

            view=View.inflate(context,R.layout.item,null);

            holder=new ViewHolder();

            holder.textView=view.findViewById(R.id.tv1);

            holder.img1=view.findViewById(R.id.img1);

 

            view.setTag(holder);

        }else {

            holder= (ViewHolder) view.getTag();

        }

 

        holder.textView.setText(data.get(i).getTitle());

        ImageLoader.getInstance().displayImage("http://365jia.cn/uploads/"+data.get(i).getPics().get(0),holder.img1,options);

 

        return view;

    }

 

    class ViewHolder{

        TextView textView;

          ImageView img1;

    } 

}

 

public class MyListView extends ListView{

    public MyListView(Context context) {

        super(context);

    }

 

    public MyListView(Context context, AttributeSet attrs) {

        super(context, attrs);

    }

 

    @Override

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

 

        int newHeight = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);

 

        super.onMeasure(widthMeasureSpec, newHeight);

 

    }

}

 

 

 

LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">


<com.handmark.pulltorefresh.library.PullToRefreshScrollView
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">

<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:id="@+id/vp"
android:layout_height="200dp">

</android.support.v4.view.ViewPager>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/lin_point"
android:orientation="horizontal"
android:gravity="center"
android:layout_gravity="bottom"></LinearLayout>

</FrameLayout>


<com.example.week3_lianxi.MyListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lv"></com.example.week3_lianxi.MyListView>
>

</LinearLayout>
</com.handmark.pulltorefresh.library.PullToRefreshScrollView>

</LinearLayout>

图片无限轮播加上下拉刷新

标签:lists   type   let   disk   lse   index   messages   长度   puts   

原文地址:https://www.cnblogs.com/xiaxinxin/p/8954950.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!