最近要做一个带滑动和点击效果的一组图片,用了差不多俩周的时间我也没搞出来。蛋疼啊。。。
今天老板给了我一个Demo,说是公司技术顾问做的。。。一看效果,hoho,正是想要的效果,心里呐喊,大牛啊
Demo中用到了从SD卡中读取图片(包括图片的名称),然后将图片以8个一组的形式显示在屏幕上,左右滑动会更换图片(滑动效果)。点击图片可以得到图片的位置。
下面贴一些关键代码:
判断SD卡是否挂载:
private static boolean isMount() { String SDState = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(SDState)) { return true; } return false; }
获取SD卡路径:
public static String getSDCartPath() { String SDCardPath = null; if (isMount()) { SDCardPath = Environment.getExternalStorageDirectory().getAbsolutePath(); } return SDCardPath; }
获取目标目录下得文件信息,列表形式返回:
public static List<String> getFiles() { List<String> apklist = new ArrayList<String>(); File[] files = new File(getSDCartPath()+PATH).listFiles(); for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.isFile()) { apklist.add(f.getPath()); } } return apklist; }
通过文件路径获取文件:
public static File findFileByName(String filePath) { File file = null; String SDCardPath = getSDCartPath(); if (SDCardPath != null) { file = new File( filePath); if (file.exists()) { return file; } } return file; }
通过文件路径生成一个输入流:
public static InputStream findStreamByName(String filePath) { InputStream inputStream = null; File file = findFileByName(filePath); try { inputStream = new BufferedInputStream(new FileInputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } return inputStream; }
将文件转换成字节存放到数组中:
public static byte[] findByteByName(String filePath) { InputStream inputStream = null; ByteArrayOutputStream byteStrem = new ByteArrayOutputStream(); try { inputStream = findStreamByName(filePath); copy(inputStream, byteStrem); // byte[] data = new byte[inputStream.available()]; // inputStream.read(data); byteStrem.flush(); return byteStrem.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } public static int copy(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024 * 4]; int readSize = -1; int result = 0; while ((readSize = in.read(buffer)) >= 0) { out.write(buffer, 0, readSize); result = calcNewNrReadSize(readSize, result); } out.flush(); return result; } protected static int calcNewNrReadSize(int nrRead, int totalNrNread) { if (totalNrNread < 0) { return totalNrNread; } if (totalNrNread > (Integer.MAX_VALUE - nrRead)) { return -1; } else { return (totalNrNread + nrRead); } }
以上方法是在工具类中的。。。
该包下得另外另个类的分别是图片的装载和View的控制,将图片加载进View中。
用图片装载类的方法获取图片:
public synchronized Bitmap loadImg(final String imageUrl) {
if (TextUtils.isEmpty(imageUrl)) {
return null;
}
return getBitmap(imageUrl);
}
private Bitmap getBitmap(final String imageUrl) {
try {
byte[] b = SDCardUtils.findByteByName(imageUrl);
if (b != null && b.length > 0) {
Bitmap bit = BitmapFactory.decodeByteArray(b, 0, b.length);
if (bit != null) {
return bit;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
工具类:获取视图中的View、数据列表
public static LayoutInflater getInflater(Context context) { if (null != context) { return (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } return null; } public static View getView(Context context, int resId) { LayoutInflater layoutInflater = getInflater(context); if (layoutInflater != null) { return layoutInflater.inflate(resId, null); } return null; } public static List<FoodstuffBean> getDatas() { List<String> files = SDCardUtils.getFiles(); List<FoodstuffBean> list = new ArrayList<FoodstuffBean>(); for (String url : files) { FoodstuffBean bean = new FoodstuffBean(url, getName(url), null, 0.00); list.add(bean); } return list; } private static String getName(String url) { return url.substring(url.lastIndexOf("/") + 1, url.length()); }
GridView适配器:
private List<FoodstuffBean> list = new ArrayList<FoodstuffBean>(); private Context context; private SyncImageLoader loader; public GridViewAdapter(Context context) { this.context = context; loader = new SyncImageLoader(); } public void setList(List<FoodstuffBean> list) { this.list = list; } @Override public int getCount() { return list.size(); } @Override public FoodstuffBean getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewCache cache; if (null == convertView) { cache = new ViewCache(); convertView = ViewUtil.getView(context, R.layout.foodstuff_gridview_item_layout); cache.imageView = (ImageView) convertView.findViewById(R.id.foodstuffICON_imageView_id); cache.textView = (TextView) convertView.findViewById(R.id.foodstuffName_textView_id); convertView.setTag(cache); } else { cache = (ViewCache) convertView.getTag(); } BindData(cache, position); return convertView; } private void BindData(ViewCache cache, int position) { FoodstuffBean item = getItem(position); cache.imageView.setImageBitmap(loader.loadImg(item.getImageURL())); cache.textView.setText(item.getName()); // cache.textView.setText("54555"); } class ViewCache { ImageView imageView; TextView textView; }
ViewPager适配器:
private static final int DEFAULT_CONUT = 8; private Context context; private List<FoodstuffBean> mList; private int surplus; private int screenCount; private boolean loop = true; public SlideScreenAdapter(Context context, List<FoodstuffBean> mList) { this.context = context; this.mList = mList; surplus = mList.size() % DEFAULT_CONUT; screenCount = (mList.size() - 1) / DEFAULT_CONUT + 1; } private View tempView = null; /* * (销毁position位置的页面) * @see android.support.v4.view.PagerAdapter#destroyItem(android.view.View, int, java.lang.Object) */ @Override public void destroyItem(View collection, int position, Object view) { tempView = (View) view; ((ViewPager) collection).removeView(tempView); } private GridViewAdapter adapter; private class CacheView { GridView gridview; } private List<FoodstuffBean> getGridViewDatas(int position) { List<FoodstuffBean> subList; int pos = position * DEFAULT_CONUT; if (position + 1 < screenCount) { subList = mList.subList(pos, pos + DEFAULT_CONUT); } else { if (surplus > 0) { subList = mList.subList(pos, pos + surplus); } else { subList = mList.subList(pos, pos + DEFAULT_CONUT); } } return subList; } /* * (初始化position位置的页面) * @see android.support.v4.view.PagerAdapter#instantiateItem(android.view.View, int) */ @Override public Object instantiateItem(View collection, int position) { View view = null; CacheView cache = null; Log.i("other", "position1=" + position); if (loop && position + 1 > screenCount) { if (position % screenCount == 0) { position = 0; Log.i("other", "position2=" + position); } else { position = position % screenCount; Log.i("other", "position3=" + position); } } List<FoodstuffBean> list = getGridViewDatas(position); if (tempView != null) { view = tempView; cache = (CacheView) view.getTag(); adapter = (GridViewAdapter) cache.gridview.getAdapter(); adapter.setList(list); tempView = null; } else { cache = new CacheView(); view = ViewUtil.getView(context, R.layout.foodstuff_screen_item_layout); adapter = new GridViewAdapter(context); adapter.setList(list); cache.gridview = (GridView) view.findViewById(R.id.foodstuff_screen_item_gridview_id); cache.gridview.setAdapter(adapter); cache.gridview.setOnItemClickListener(new GridViewListener(context)); view.setTag(cache); } adapter.notifyDataSetChanged(); ((ViewPager) collection).addView(view);// , 0 return view; } @Override public void finishUpdate(View arg0) { } @Override public void startUpdate(View arg0) { } @Override public int getCount() { if (loop) { return Integer.MAX_VALUE; } else { return screenCount; } } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public void restoreState(Parcelable arg0, ClassLoader arg1) { } @Override public Parcelable saveState() { return null; }
实体类:
private String imageURL; private String name; private String details; private double price; public FoodstuffBean() { } public FoodstuffBean(String imageURL, String name, String details, double price) { this.imageURL = imageURL; this.name = name; this.details = details; this.price = price; } public String getImageURL() { return imageURL; } public void setImageURL(String imageURL) { this.imageURL = imageURL; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; }
设置GridView中的事件监听器:
private Context context; public GridViewListener(Context context) { this.context = context; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(context, "position= " + position, Toast.LENGTH_SHORT).show(); }
MainActivity:
slideScreen = (ViewPager) findViewById(R.id.foodstuff_slideScreen_id); adapter = new SlideScreenAdapter(getApplicationContext(), ViewUtil.getDatas()); slideScreen.setAdapter(adapter);