这些东西都要调用依赖library 和 Tablayout 还要在manifests里配置
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:name=".MApplication"
main.xml 布局
RelativeLayout
<android.support.v4.widget.DrawerLayout android:id="@+id/drawerlayout" android:layout_width="match_parent" android:layout_height="match_parent" > <com.example.kson.tablayout.widget.HorizontalScollTabhost android:id="@+id/horizontal" android:layout_width="368dp" android:layout_height="wrap_content" tools:layout_editor_absoluteY="0dp" tools:layout_editor_absoluteX="8dp"></com.example.kson.tablayout.widget.HorizontalScollTabhost> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff" android:layout_gravity="left"> <TextView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="match_parent" android:text="我喜欢你" /> </LinearLayout> </android.support.v4.widget.DrawerLayout> MainActivity 文件import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import com.example.kson.tablayout.widget.HorizontalScollTabhost; import com.example.kson.tablayout.widget.bean.CategoryBean; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private HorizontalScollTabhost horizontal; private List<String> titleList;//这个集合是定义的判断 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //刚才一直报错是因为fragment后面加了个数字 //导入一个架包 //初始化控件horizontal 这个控件代表的是整个页面 horizontal = (HorizontalScollTabhost) findViewById(R.id.horizontal); //因为下面的方法里要两个集合的参数 List<CategoryBean> list=new ArrayList<>(); List<Fragment> fragments=new ArrayList<>();//这是fragment CategoryBean cate=new CategoryBean(); cate.id="iOS"; cate.name="福利"; list.add(cate); cate=new CategoryBean(); cate.id="iOS"; cate.name="Android"; list.add(cate); cate=new CategoryBean(); cate.id="iOS"; cate.name="IOS"; list.add(cate); cate=new CategoryBean(); cate.id="iOS"; cate.name="休息视频"; list.add(cate); cate=new CategoryBean(); cate.id="iOS"; cate.name="拓展资源"; list.add(cate); cate=new CategoryBean(); cate.id="iOS"; cate.name="前端"; list.add(cate); cate=new CategoryBean(); cate.id="iOS"; cate.name="all"; list.add(cate); //这里是替换的方法 后面括号里的东西是借口 Fragment instance = new MYfragment().getInstance("福利"); fragments.add(instance); Fragment android = new MYfragment().getInstance("Android"); fragments.add(android); Fragment iOS = new MYfragment().getInstance("iOS"); fragments.add(iOS); Fragment instance1 = new MYfragment().getInstance("休息视频"); fragments.add(instance1); Fragment instance2 = new MYfragment().getInstance("拓展资源"); fragments.add(instance2); Fragment instance3 = new MYfragment().getInstance("前端"); fragments.add(instance3); Fragment all = new MYfragment().getInstance("all"); fragments.add(all); horizontal.diaplay(list,fragments); } fragment ---------------------------------------------------------------public class MYfragment extends Fragment{ ArrayList<Integer> listt=new ArrayList<>(); private List<Jixilei.ResultsBean> list = new ArrayList<>(); List<String> imagUrlList =new ArrayList<>(); private MyAdapter myAdapter; private int page_num = 1; private ImageLoader lmageloader; private View view; private PullToRefreshListView refreshListView; private String param; private ViewPager viewPager; private ImageLoader imageLoader; private LinearLayout linearlayout; private ArrayList<ImageView> listIV; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { //得到当前的position int position = viewPager.getCurrentItem(); position++; viewPager.setCurrentItem(position); sendMsg(); } }; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment1, null); return view; } //因为要返回 把请求数据写在onresume 里 但下面的适配器不能判断 因为生命周期没有走完那里面不是空 @Override public void onResume() { super.onResume(); getData(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //这里是另一个布局要当成头布局来添加到PullToRefreshListView这个里面 View inflate = View.inflate(getActivity(), R.layout.vp, null); viewPager =inflate.findViewById(R.id.viewpager); linearlayout =inflate.findViewById(R.id.linearlayout); refreshListView = view.findViewById(R.id.refresh_list_view); //只有用了这个方法才能添加头布局 ListView listView = refreshListView.getRefreshableView(); listView.addHeaderView(inflate); //shujuyuan(); // getData(); //这是拿到mainactivity里的值 Bundle arguments = getArguments(); param = arguments.getString("name"); refreshListView.setMode(PullToRefreshBase.Mode.BOTH); //布局 ILoadingLayout startLabels = refreshListView.getLoadingLayoutProxy(true, false); startLabels.setPullLabel("下拉刷新"); startLabels.setRefreshingLabel("正在刷新..."); startLabels.setReleaseLabel("放开刷新"); ILoadingLayout endLabels = refreshListView.getLoadingLayoutProxy( false, true); endLabels.setPullLabel("上拉刷新"); endLabels.setRefreshingLabel("正在载入..."); endLabels.setReleaseLabel("放开刷新..."); //设置监听 refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() { //下拉加载的数据 @Override public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) { getRefreshData(); } @Override public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) { //上拉加载的时候 page_num加一 page_num ++; getData(); } }); } //轮播发送东西 private void sendMsg() { handler.sendEmptyMessageDelayed(0, 2000); } //viewpager 轮播 // private void shujuyuan() { // listt.add(R.drawable.m1); // listt.add(R.drawable.m2); // listt.add(R.drawable.m3); // } /** * 这个方法是刚进入界面的时候请求数据,,,,和上拉加载的时候不停的请求数据 * * page_num每次加载的时候会加1,,,这个方法中数据添加在list集合的后面 * * 请求设置适配器之后 刷新停止 */ //这里是请求的总数据 private void getData() { AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... voids) { try { String path = "http://gank.io/api/data/"+ URLEncoder.encode(param,"utf-8")+"/10/"+page_num; URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); //获取 int responseCode = connection.getResponseCode(); if (responseCode == 200){ InputStream inputStream = connection.getInputStream(); String json = streamToString(inputStream,"utf-8"); return json; } } catch (Exception e) { e.printStackTrace(); } return ""; } @Override protected void onPostExecute(String s) { //解析 Gson gson = new Gson(); Jixilei dataDataBean = gson.fromJson(s, Jixilei.class); /** * 判断数据非空 */ if (dataDataBean != null && dataDataBean.getResults() != null){ //数据添加 list.addAll(dataDataBean.getResults());//拿到的是每一页的数据的集合 List<Jixilei.ResultsBean> results = dataDataBean.getResults(); for (int i=0; i<results.size();i++) { if(results.get(i).getImages()!=null) { Log.e("wzq", "onPostExecute: "+results.get(i).getImages() ); imagUrlList.add(results.get(i).getImages().get(0)); } } //设置适配器 setAdapter(); viewPager.setAdapter(new Myviewpager()); initDot();//小点的方法 viewPager.setCurrentItem(1000*list.size()); sendMsg(); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { for (int x = 0; x < listIV.size(); x++) { if (position % imagUrlList.size() == x) { listIV.get(position % imagUrlList.size()).setImageResource(R.drawable.dot_focus); } else { listIV.get(x).setImageResource(R.drawable.dot_normal); } } } @Override public void onPageScrollStateChanged(int state) { } }); //刷新停止 refreshListView.onRefreshComplete(); } } }; asyncTask.execute(); } /** * 获取刷新时的数据...刷新时只访问第一页的数据,,,,刷新的数据需要添加到集合的前边 * * 刷新完成,,设置适配器之后刷新需要停止 */ private void getRefreshData() { AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... voids) { try { String path = "http://gank.io/api/data/"+ URLEncoder.encode(param,"utf-8")+"/10/1"; URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); //获取 int responseCode = connection.getResponseCode(); if (responseCode == 200){ InputStream inputStream = connection.getInputStream(); String json = streamToString(inputStream,"utf-8"); return json; } } catch (Exception e) { e.printStackTrace(); } return ""; } @Override protected void onPostExecute(String s) { //解析 Gson gson = new Gson(); Jixilei dataDataBean = gson.fromJson(s, Jixilei.class); /** * 判断数据非空 */ if (dataDataBean != null && dataDataBean.getResults() != null){ //数据添加 list.addAll(0,dataDataBean.getResults()); //设置适配器 setAdapter(); //停止刷新 refreshListView.onRefreshComplete(); } } }; asyncTask.execute(); } private String streamToString(InputStream inputStream,String charset) { try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String s = null; StringBuilder builder = new StringBuilder(); while ((s = bufferedReader.readLine()) != null){ builder.append(s); } bufferedReader.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } //设置适配器 private void setAdapter() { // if (myAdapter == null){ myAdapter = new MyAdapter(getActivity(), (ArrayList<Jixilei.ResultsBean>) list); refreshListView.setAdapter(myAdapter); // }else { // / myAdapter.notifyDataSetChanged(); // } } public static Fragment getInstance(String name) { MYfragment frangment=new MYfragment(); Bundle bundle=new Bundle(); bundle.putString("name", name); frangment.setArguments(bundle); return frangment; } class Myviewpager 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 iv=new ImageView(getActivity()); iv.setScaleType(ImageView.ScaleType.FIT_XY); if (imagUrlList .size() != 0){ Log.e("wzq", "instantiateItem: "+imagUrlList.get(0) ); //iv.setImageResource(listt.get(position%listt.size())); ImageLoader.getInstance().displayImage(imagUrlList.get(position%imagUrlList.size()),iv); container.addView(iv); } return iv; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } } //小点方法 private void initDot() { linearlayout.removeAllViews(); listIV = new ArrayList<ImageView>(); if(listIV !=null){ listIV.clear(); } for (int x = 0; x < imagUrlList.size(); x++) { ImageView iv = new ImageView(getActivity()); if (x == 0) { iv.setImageResource(R.drawable.dot_focus); } else { iv.setImageResource(R.drawable.dot_normal); } listIV.add(iv); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20, 20); params.setMargins(10, 0, 10, 0); linearlayout.addView(iv, params); } } //删除的方法 @Override public void onDestroy() { super.onDestroy(); handler.removeCallbacksAndMessages(null); }图片请求的设置-------------------------------------------------------------------------------public class ImageLoaderUtil { /** * 初始化的方法 * * @param */ public static void init(Context context) { File cacheDir = StorageUtils.getCacheDirectory(context); //缓存文件夹路径 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) .threadPoolSize(3) // default 线程池内加载的数量 .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 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 getDefaultOption() { 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.IN_SAMPLE_POWER_OF_2) // default 设置图片以如何的编码方式显示 .bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型 .displayer(new SimpleBitmapDisplayer()) // default 还可以设置圆角图片new RoundedBitmapDisplayer(20) .build(); return options; }调用那个方法--------------------------------------------------------------------------------------------public class MApplication extends Application { @Override public void onCreate() { super.onCreate(); ImageLoaderUtil.init(this); } } MaAdapter适配器-------------------------------------------------------------------------------------------------------public class MyAdapter extends BaseAdapter { private Context context; private ArrayList<Jixilei.ResultsBean> list; public MyAdapter(Context context, ArrayList<Jixilei.ResultsBean> list) { this.context = context; this.list = list; } @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 holder; if (view == null){ view=View.inflate(context,R.layout.item_layout,null); holder = new ViewHolder(); holder.imageView = (ImageView) view.findViewById(R.id.image_view); holder.textView = (TextView) view.findViewById(R.id.text_title); view.setTag(holder); }else { holder = (ViewHolder) view.getTag(); } //设置 holder.textView.setText(list.get(i).getDesc()); /** * 加载图片之前需要判断一下是否有图片的地址 */ if (list.get(i).getImages() != null){ ImageLoader.getInstance().displayImage(list.get(i).getImages().get(0)+"?imageView2/0/w/100",holder.imageView,ImageLoaderUtil.getDefaultOption()); } return view; } private class ViewHolder{ ImageView imageView; TextView textView; }
布局 ----------------------------------------------------------------------------------
fragment1<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.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"></com.handmark.pulltorefresh.library.PullToRefreshListView> </LinearLayout>item_layout-----------------------------------------------------------------------布局<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:padding="10dp"> <ImageView android:src="@mipmap/ic_launcher" android:id="@+id/image_view" android:layout_width="100dp" android:layout_height="100dp" /> <TextView android:id="@+id/text_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" /> </LinearLayout>添加头布局-----------------------------------------------------------------------------------------vp<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="200dp"/> <LinearLayout android:id="@+id/linearlayout" android:gravity="center" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:paddingBottom="20dp" /> </LinearLayout>