PullToRefreshScrollView

来源:互联网 发布:java listview 删除 编辑:程序博客网 时间:2024/05/22 01:38

test


build.gradle

compile 'com.android.support:design:26.0.0-alpha1'compile 'com.github.userswlwork:pull-to-refresh:1.0.0'compile 'com.youth.banner:banner:1.4.10'

<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    android:orientation="vertical"    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    android:layout_height="match_parent" tools:context="com.example.weektest03.MainActivity">    <FrameLayout        android:id="@+id/frame"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="9">    </FrameLayout>    <RadioGroup        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1"        android:id="@+id/rg"        android:orientation="horizontal">        <RadioButton            android:layout_width="0dp"            android:layout_height="match_parent"            android:id="@+id/rb1"            android:layout_weight="1"            android:button="@null"            android:text="首页"            android:layout_gravity="center"            android:gravity="center"            android:textColor="#f00"/>        <RadioButton            android:layout_width="0dp"            android:layout_height="match_parent"            android:id="@+id/rb2"            android:layout_weight="1"            android:button="@null"            android:text="发现"            android:layout_gravity="center"            android:gravity="center"/>        <RadioButton            android:layout_width="0dp"            android:layout_height="match_parent"            android:id="@+id/rb3"            android:layout_weight="1"            android:button="@null"            android:text="下载"            android:layout_gravity="center"            android:gravity="center"/>        <RadioButton            android:layout_width="0dp"            android:layout_height="match_parent"            android:id="@+id/rb4"            android:layout_weight="1"            android:button="@null"            android:text="我的"            android:layout_gravity="center"            android:gravity="center"/>    </RadioGroup></LinearLayout>
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    xmlns:app="http://schemas.android.com/apk/res-auto"    android:orientation="vertical">    <android.support.design.widget.TabLayout        android:id="@+id/tablayout"        android:layout_width="match_parent"        android:layout_height="50dp"        app:tabGravity="center"        app:tabIndicatorColor="@color/colorAccent"        app:tabMode="scrollable"        app:tabSelectedTextColor="@color/colorPrimaryDark"        app:tabTextColor="@color/colorPrimary">    </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.support.v4.view.ViewPager></LinearLayout>


<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    xmlns:ptr="http://schemas.android.com/apk/res-auto">    <com.handmark.pulltorefresh.library.PullToRefreshScrollView        android:id="@+id/psv"        android:layout_width="match_parent"        android:layout_height="match_parent"        ptr:ptrDrawable="@drawable/default_ptr_flip"        ptr:ptrAnimationStyle="flip"        ptr:ptrHeaderBackground="#383838"        ptr:ptrHeaderTextColor="#FFFFFF">        <LinearLayout            android:layout_width="match_parent"            android:layout_height="match_parent"            android:orientation="vertical">            <com.youth.banner.Banner                android:layout_width="match_parent"                android:layout_height="200dp"                android:id="@+id/banner"></com.youth.banner.Banner>            <com.example.weektest03.MyListView                android:layout_width="match_parent"                android:layout_height="match_parent"                android:id="@+id/lv">            </com.example.weektest03.MyListView>        </LinearLayout>    </com.handmark.pulltorefresh.library.PullToRefreshScrollView></LinearLayout>

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <ImageView        android:id="@+id/img"        android:layout_width="100dp"        android:layout_height="100dp"        android:src="@mipmap/ic_launcher"/>    <TextView        android:id="@+id/title"        android:layout_width="match_parent"        android:layout_height="wrap_content" /></LinearLayout>

MainActivity

import android.support.annotation.IdRes;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.RadioGroup;public class MainActivity extends AppCompatActivity {    private RadioGroup rg;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        rg = (RadioGroup) findViewById(R.id.rg);        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {            @Override            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {                switch (i){                    case R.id.rb1:                        getSupportFragmentManager().beginTransaction().replace(R.id.frame,new F1()).commit();                        break;                }            }        });        getSupportFragmentManager().beginTransaction().replace(R.id.frame,new F1()).commit();    }}


F1

import android.os.Bundle;import android.support.annotation.Nullable;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.ViewPager;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import com.handmark.pulltorefresh.library.PullToRefreshScrollView;import java.util.ArrayList;import java.util.List;public class F1 extends Fragment{    private ViewPager vp;    private TabLayout tablayout;    private List<String> tabs=new ArrayList<>();    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View v = inflater.inflate(R.layout.f1, null);        tablayout =(TabLayout) v.findViewById(R.id.tablayout);        vp = (ViewPager) v.findViewById(R.id.vp);        return v;    }    @Override    public void onActivityCreated(@Nullable Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);        tabs.add("推荐");        tabs.add("课程");        tabs.add("实战");        tabs.add("职业路径");        vp.setAdapter(new MyPagerAdapter(getChildFragmentManager()));        tablayout.setupWithViewPager(vp);        vp.setOffscreenPageLimit(tabs.size());    }    class MyPagerAdapter extends FragmentPagerAdapter{        public MyPagerAdapter(FragmentManager fm) {            super(fm);        }        @Override        public CharSequence getPageTitle(int position) {            return tabs.get(position);        }        @Override        public Fragment getItem(int position) {            Fragment f=null;            switch (position){                case 0:                    f=new TuiJianFragment();                    break;                            }            return f;        }        @Override        public int getCount() {            return tabs.size();        }    }}

TuiJianFragmentimport android.os.AsyncTask;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.support.v4.view.ViewPager;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ScrollView;import com.google.gson.Gson;import com.google.gson.JsonArray;import com.google.gson.reflect.TypeToken;import com.handmark.pulltorefresh.library.ILoadingLayout;import com.handmark.pulltorefresh.library.PullToRefreshBase;import com.handmark.pulltorefresh.library.PullToRefreshScrollView;import com.youth.banner.Banner;import org.json.JSONArray;import java.lang.reflect.Type;import java.util.ArrayList;import java.util.List;public class TuiJianFragment extends Fragment{    private PullToRefreshScrollView psv;    private MyListView lv;    private int page=2;    private int operType=1;    private List<Result.DataBean> list=new ArrayList<>();    private String url="http://mnews.gw.com.cn/wap/data/news/xbsjxw/page_"+page+".json";    private MyListViewAdapter adapter;    private Banner banner;    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View v = inflater.inflate(R.layout.tuijian, container,false);        psv = (PullToRefreshScrollView) v.findViewById(R.id.psv);        lv = (MyListView) v.findViewById(R.id.lv);        banner = (Banner) v.findViewById(R.id.banner);        initpulltorefresh();        initBanner();        requestNetData();        return v;    }    public void initBanner(){        List<String> urls=new ArrayList<>();        urls.add("http://pic8.nipic.com/20100701/5290458_114840036316_2.jpg");        urls.add("http://pic2.nipic.com/20090424/1468853_230119053_2.jpg");        urls.add("http://img3.3lian.com/2013/s1/20/d/57.jpg");        urls.add("http://pic39.nipic.com/20140226/18071023_164300608000_2.jpg");        urls.add("http://a0.att.hudong.com/15/08/300218769736132194086202411_950.jpg");        banner.setImageLoader(new MyBannerLoader());//添加自定义的图片加载器        banner.setImages(urls);//设置图片资源        banner.start();//开始轮播    }    public void requestNetData(){        MyAsynTask myAsynTask=new MyAsynTask(new MyAsynTask.Icallbacks() {            @Override            public void updataUiByjson(String jsonstr) {                Log.d("zzz","********"+jsonstr);                //json串最外层是[] ,首先要构造的对象 是 JSONArray                List<Result> lists=new ArrayList<>();                Type type=new TypeToken<List<Result>>(){}.getType();                Gson gson=new Gson();                lists = gson.fromJson(jsonstr, type);                if(operType==1){                    list.clear();                    list.addAll(0,lists.get(0).getData());                    Log.d("zzz","********"+list.get(0).getTitle());                }else {                    list.addAll(lists.get(0).getData());                }                setAdapter();                lv.postDelayed(new Runnable() {                    @Override                    public void run() {                        psv.onRefreshComplete();                    }                },1000);            }        });        myAsynTask.execute(url);    }    private void setAdapter(){        if(adapter==null){            adapter = new MyListViewAdapter(list, getActivity());            lv.setAdapter(adapter);        }else {            adapter.notifyDataSetChanged();        }    }    public void initpulltorefresh(){        psv.setMode(PullToRefreshBase.Mode.BOTH);        ILoadingLayout startLayout = psv.getLoadingLayoutProxy(true, false);        startLayout.setPullLabel("下拉刷新");        startLayout.setRefreshingLabel("正在刷新");        startLayout.setReleaseLabel("放开刷新");        ILoadingLayout endLayout = psv.getLoadingLayoutProxy(false, true);        endLayout.setPullLabel("上拉刷新");        endLayout.setRefreshingLabel("正在刷新");        endLayout.setReleaseLabel("放开刷新");        psv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {            @Override            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> pullToRefreshBase) {                page=1;                operType=1;                requestNetData();            }            @Override            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> pullToRefreshBase) {                page++;                operType=2;                requestNetData();            }        });    }}

MyBannerLoader

import android.content.Context;import android.widget.ImageView;import com.youth.banner.loader.ImageLoader;public class MyBannerLoader extends ImageLoader{    @Override    public void displayImage(Context context, Object path, ImageView imageView) {        com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(path.toString(),imageView);    }}

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 expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,                MeasureSpec.AT_MOST);        super.onMeasure(widthMeasureSpec, expandSpec);    }}

MyListViewAdapter

import android.content.Context;import android.graphics.Bitmap;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 java.util.List;public class MyListViewAdapter extends BaseAdapter{    private List<Result.DataBean> list;    private Context context;    private DisplayImageOptions options;    public MyListViewAdapter(List<Result.DataBean> list, Context context) {        this.list = list;        this.context = context;        options=new DisplayImageOptions.Builder()                .cacheInMemory(true)//使用内存缓存                .cacheOnDisk(true)//使用磁盘缓存                .bitmapConfig(Bitmap.Config.RGB_565)//设置图片格式                .showImageOnLoading(R.mipmap.ic_launcher) // 设置图片下载期间显示的图片                .showImageForEmptyUri(R.mipmap.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片                .showImageOnFail(R.mipmap.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片                .build();    }    @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) {        ViewHolder vh;        if(view==null){            vh = new ViewHolder();            view = View.inflate(context, R.layout.lv_child, null);            vh.img=view.findViewById(R.id.img);            vh.title=view.findViewById(R.id.title);            view.setTag(vh);        }else {            vh = (ViewHolder) view.getTag();        }        vh.title.setText(list.get(i).getTitle());        String img = list.get(i).getImg();        ImageLoader.getInstance().displayImage(img,vh.img,options);        return view;    }    class ViewHolder{        ImageView img;        TextView title;    }}


MyAsynTask

import android.os.AsyncTask;import android.util.Log;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;public class MyAsynTask extends AsyncTask<String,Void,String>{    private Icallbacks icallbacks;    public MyAsynTask(Icallbacks icallbacks) {        this.icallbacks = icallbacks;    }    private MyAsynTask(){}    @Override    protected String doInBackground(String... strings) {        try {            URL url=new URL(strings[0]);            HttpURLConnection connection = (HttpURLConnection) url.openConnection();            connection.setRequestMethod("GET");            connection.setConnectTimeout(2000);            connection.setReadTimeout(2000);            int code = connection.getResponseCode();            if(code==200){                InputStream inputStream = connection.getInputStream();                byte[] bytes=new byte[1024];                int len=0;                ByteArrayOutputStream bos=new ByteArrayOutputStream();                while ((len=inputStream.read(bytes))!=-1){                    bos.write(bytes,0,len);                }                String string = bos.toString();                bos.close();                Log.d("zzz","*******"+string);                return string;            }        } catch (Exception e) {            e.printStackTrace();        }        return "";    }    @Override    protected void onPostExecute(String s) {        super.onPostExecute(s);        icallbacks.updataUiByjson(s);    }    public interface Icallbacks{        void updataUiByjson(String jsonstr);    }}


MyApplication

import android.app.Application;import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;import java.io.File;public class MyApplication extends Application{    @Override    public void onCreate() {        super.onCreate();        File cachefile=getExternalCacheDir();        //自定义的缓存路径//        File cachefile=new File(Environment.getExternalStorageDirectory().getPath()+"/abc/a");        //进行框架初使化操作-全局配置        ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(this)                .memoryCacheExtraOptions(480, 800)//缓存图片最大的长和宽                .threadPoolSize(2)//线程池的数量                .threadPriority(4)                .memoryCacheSize(5*1024*1024)//设置内存缓存区大小                .diskCacheSize(20*1024*1024)//设置sd卡缓存区大小                .diskCache(new UnlimitedDiscCache(cachefile))//自定义磁盘缓存目录                .writeDebugLogs()//打印日志内容                .diskCacheFileNameGenerator(new Md5FileNameGenerator())//给缓存的文件名进行md5加密处理                .build();        ImageLoader.getInstance().init(configuration);    }}