当前位置: 代码迷 >> Android >> Android初级教程_图片混排成效和ViewPager的使用
  详细解决方案

Android初级教程_图片混排成效和ViewPager的使用

热度:8   发布时间:2016-05-01 17:40:45.0
Android初级教程_图片混排效果和ViewPager的使用

前段时间公司需要实现图片混排的效果,类似"美丽说"那样,宽度一样,高度不一.总共有3列.每次加载更多的时候都是往最低的那列添加图片,这样就不会出现有的列非常多的图片,而有的列图片很少.首先申明的是这个例子是根据别人的程序基础上改的:https://github.com/dodola/android_waterfall再次感谢.!

效果如下图所示:




当滑倒底部的时候如果还有图片则自动加载下一页.

代码实现如下:

首先自定义布局:

public class MyLinearLayout extends LinearLayout {	private Map<Integer, Integer> map;	private ArrayList<LinearLayout> waterfall_items;	private Context context;	private Display display;	private int itemWidth;	public MyLinearLayout(Context context, AttributeSet attrs) {		super(context, attrs);	}	public MyLinearLayout(Context context) {		super(context);	}	/**	 * 初始化容器 	 * @param columnCount	 *            列数	 * @param paddingLeft	 * @param paddingTop	 * @param paddingRight	 * @param paddingBottom	 */	public void initLayout(int columnCount, int paddingLeft, int paddingTop,			int paddingRight, int paddingBottom) {				if (columnCount < 1)			columnCount = 3;				Constans.COLUMN_COUNT = columnCount;				waterfall_items = new ArrayList<LinearLayout>();		map = new HashMap<Integer, Integer>();		for (int i = 0; i < columnCount; i++) {			map.put(i, 0);		}		context = getContext();		WindowManager windowManager = (WindowManager) context				.getSystemService(Context.WINDOW_SERVICE);		display = windowManager.getDefaultDisplay();		itemWidth = display.getWidth() / columnCount;// 根据屏幕大小计算每列大小		for (int i = 0; i < columnCount; i++) {			LinearLayout itemLayout = new LinearLayout(context);			LinearLayout.LayoutParams itemParam = new LinearLayout.LayoutParams(					itemWidth, LayoutParams.WRAP_CONTENT);			itemLayout.setPadding(1, 2, 1, 2);			itemLayout.setOrientation(LinearLayout.VERTICAL);			itemLayout.setLayoutParams(itemParam);			waterfall_items.add(itemLayout);			this.addView(itemLayout);		}	}	/**	 * 贴图	 * @param article 文章实体	 * @param columnIndex 列索引	 */	private void addImage(final Article article, int columnIndex) {		ImageView item = (ImageView) LayoutInflater.from(context).inflate(				R.layout.waterfallitem, null);		waterfall_items.get(columnIndex).addView(item);		//int inSampleSize = 1;		int h = 0;		// int originalWidth = article.getWidth();		 int originalHieght = article.getHeight();		//		// int screenHeight = display.getHeight() / 7;		// int screenWidth = display.getWidth() / 7;		// float heightRatio = (float) Math.ceil(article.getHeight()		// / screenHeight);		// float widthRatio = (float) (Math.ceil(originalWidth / screenWidth));		// if (heightRatio >= 1 && widthRatio >= 1) {		// if (heightRatio > widthRatio) {		// inSampleSize = (int) heightRatio;		// } else {		// inSampleSize = (int) widthRatio;		// }		// h = originalHieght;// inSampleSize;		// } else {		// h = originalHieght;		// }		h = originalHieght;		int value = map.get(columnIndex);		map.put(columnIndex, value+h);				TaskParam param = new TaskParam();		param.setItemWidth(itemWidth);		Bitmap defaultImage = BitmapFactory.decodeResource(getResources(),				R.drawable.loading);		ImageLoaderTask task = new ImageLoaderTask(item, display,				article.getImage(), article, defaultImage, param);		task.execute(param);		item.setOnClickListener(new View.OnClickListener() {			@Override			public void onClick(View v) {				Intent intent = new Intent();				intent.setClassName(context.getPackageName(),						GirlDetailActivity.class.getName());				intent.putExtra("id", article.getId());				context.startActivity(intent);			}		});					}	/**	 * 把图片集合填充到容器里	 * @param articles	 */	public void setAdapter(List<Article> articles) {		for (int i = 0; i < articles.size(); i++) {			Article article = articles.get(i);			addImage(article, getLowestColumn());		}	}	public int getLowestColumn(){		List<Integer> list = new ArrayList<Integer>();		list.addAll(map.values());		Collections.sort(list);		int min = list.get(0);		Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();		for (Map.Entry<Integer, Integer> entry : entrySet) {			if(min==entry.getValue()){				return entry.getKey();			}		}		return 0;	}}

界面Activity:

Handler handler = new Handler() {		public void handleMessage(android.os.Message msg) {			waterfall_container.setAdapter(articles);//设置数据				if(countImage==currentCount){					System.out.println("已经到最后");					textView.setVisibility(View.VISIBLE);				}		}	};	@Override	public void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.main);			initLayout();	}	private void initLayout() {				textView = (TextView) findViewById(R.id.tv_tip);		waterfall_scroll = (LazyScrollView) findViewById(R.id.waterfall_scroll);		waterfall_scroll.getView();		waterfall_scroll.setOnScrollListener(new OnScrollListener() {			@Override			public void onTop() {				Log.d("LazyScroll", "Scroll to top");			}			@Override			public void onScroll() {				Log.d("LazyScroll", "Scroll");			}			@Override			public void onBottom() {				// 滚动到最底端				if(countImage!=currentCount) {					new Thread(new LoadMyArticle()).start();//加载下一页				}			}		});		waterfall_container = (MyLinearLayout) this				.findViewById(R.id.waterfall_container);		//初始化容器		waterfall_container.initLayout(3, 2, 2, 2, 2);				// 加载所有图片路径		new Thread(new LoadMyArticle()).start();	}	public final class LoadMyArticle implements Runnable {		@Override		public void run() {			try {				url_article_list.append("&page=").append(page++);				InputStream inputStream = GsonJsonParser						.getIputStream(url_article_list.toString());				ArticleJson articleJson = (ArticleJson) GsonJsonParser						.parseStreamToObject(inputStream, ArticleJson.class);				countImage = articleJson.getTotal();				articles = articleJson.getData();				currentCount += articles.size();				handler.sendEmptyMessage(1);			} catch (IOException e) {				e.printStackTrace();			}		}	}

当点击某一张图片的时候,进入图片详情.这里使用了VIewPager来实现的.效果如下:



实现如下:

private ViewPager viewPager;	private List<ImageView> imageViews = new ArrayList<ImageView>();	private List<Photo> photos;	private Map<Integer,SoftReference<Bitmap>> cache = new HashMap<Integer,SoftReference<Bitmap>>();	private ProgressBar pb;	private MyAsyncTask myAsyncTask;	int screenWidth ;	int screenHeight; 	Handler handler = new Handler(){		public void handleMessage(android.os.Message msg) {			switch (msg.what) {			case 1:				if(photos!=null&&photos.size()>0){					for (int i = 0; i < photos.size(); i++) {						ImageView imageView = new ImageView(GirlDetailActivity.this);						imageViews.add(imageView);					}					viewPager.setAdapter(new AwesomePagerAdapter());					myAsyncTask = new MyAsyncTask(0);					myAsyncTask.execute(photos.get(0).getImage());				}				break;			}		}	};	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		requestWindowFeature(Window.FEATURE_NO_TITLE);		setContentView(R.layout.girls_detail);		Display display = getWindowManager().getDefaultDisplay();		display = getWindowManager().getDefaultDisplay();		screenWidth = display.getWidth();		screenHeight = display.getHeight();		init();		Intent intent = getIntent();		String id = intent.getStringExtra("id");		StringBuffer url = new StringBuffer(url);		url.append("?id=").append(id).append("&type=2");		new Thread(new LoadImagePath(url.toString())).start();	}	public void init(){				pb = (ProgressBar) findViewById(R.id.widget);				viewPager = (ViewPager) findViewById(R.id.awesomepager);				viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {			@Override			public void onPageSelected(final int position) {				String image_path = photos.get(position).getImage();				pb.setVisibility(View.GONE);				if(cache.containsKey(position)){					Bitmap bitmap = cache.get(position).get();					if(bitmap!=null){						imageViews.get(position).setImageBitmap(bitmap);					}else {						if(!myAsyncTask.isCancelled()){							System.out.println("任务被取消");							myAsyncTask.cancel(true);						}						myAsyncTask = new MyAsyncTask(position);						myAsyncTask.execute(image_path);					}				}else {					if(!myAsyncTask.isCancelled()){						System.out.println("任务被取消");						myAsyncTask.cancel(true);					}					myAsyncTask = new MyAsyncTask(position);					myAsyncTask.execute(image_path);				}			}						@Override			public void onPageScrolled(int position, float positionOffset,					int positionOffsetPixels) {							}						@Override			public void onPageScrollStateChanged(int arg0) {							}		});	}	public class AwesomePagerAdapter extends PagerAdapter {		@Override		public int getCount() {			return imageViews.size();		}		@Override		public Object instantiateItem(View collection, int position) {			ImageView imageView = imageViews.get(position);			((ViewPager) collection).addView(imageView, 0);			return imageViews.get(position);		}		@Override		public void destroyItem(View collection, int position, Object view) {			((ViewPager) collection).removeView(imageViews.get(position));		}		@Override		public boolean isViewFromObject(View view, Object object) {			// System.out.println("isViewFromObject");			return view == (object);		}		@Override		public void finishUpdate(View arg0) {			// System.out.println("finishUpdate");		}		@Override		public void restoreState(Parcelable arg0, ClassLoader arg1) {			// System.out.println("restoreState");		}		@Override		public Parcelable saveState() {			// System.out.println("saveState");			return null;		}		@Override		public void startUpdate(View arg0) {		}	}	@Override	public void onStop() {		super.onStop();	}	@Override	protected void onDestroy() {		super.onDestroy();	}		private final class LoadImagePath implements Runnable{		private String url;		public LoadImagePath(String url){			this.url = url;		}		@Override		public void run() {			try {				InputStream in = JsonParse.getIputStream(url);				PhotoDetailJson photoDetailJson = (PhotoDetailJson) GsonJsonParser.parseStreamToObject(in, PhotoDetailJson.class);				PhotoDetail detail = photoDetailJson.getData();				photos = detail.getPhoto();				handler.sendEmptyMessage(1);			} catch (IOException e) {				e.printStackTrace();			}		}	}		public final class MyAsyncTask extends AsyncTask<String, Void, Bitmap>{		private int position;		public MyAsyncTask(int position){			this.position = position;		}		@Override		protected Bitmap doInBackground(String... params) {			String path = params[0];			try {				InputStream in = JsonParse.getIputStream(path);				//如果屏幕超过800*480				if(screenWidth>480&&screenHeight>800){//960x540					screenWidth = 480;					screenHeight = 800;				}				 Bitmap bitmap = ImageUtil.getSizedBitmap(screenWidth, screenHeight, in);				 cache.put(position, new SoftReference<Bitmap>(bitmap));				 return bitmap;			} catch (IOException e) {				e.printStackTrace();			} catch (Exception e) {				e.printStackTrace();			}			return null;		}				@Override		protected void onPostExecute(Bitmap result) {			super.onPostExecute(result);			imageViews.get(position).setImageBitmap(result);			pb.setVisibility(View.GONE);		}				@Override		protected void onPreExecute() {			super.onPreExecute();			pb.setVisibility(View.VISIBLE);			imageViews.get(position).setImageResource(R.drawable.wait_girl_detail);		}			}

完毕!

欢迎转载,转载请注明出处:http://blog.csdn.net/johnny901114/article/details/7835139


谢谢大家.希望对你有帮助.有事请留言....





  相关解决方案