前段时间公司需要实现图片混排的效果,类似"美丽说"那样,宽度一样,高度不一.总共有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
谢谢大家.希望对你有帮助.有事请留言....
分享到:
相关推荐
文字排版,特别是在Pad上,由于屏幕大,所以经常会用到图文混排的方式。该项目就是基于Android开发的非html实现的图文混排。注释详细,一看就懂!
此例子可以有效地解决类似于QQ/微信中的图文混排效果,支持任意位置编辑 当内容太多时,ScrollView自动滚动到最下边 如果您需要引用该例子,请保留我的信息,欢迎大家一起探讨 另外在此例子中还有一个小问题,在...
今天项目中碰见一个问题就是有多行文字但是有个图标必须是在一行文字的首位或者最后展示drawableleft等方法已经不能满足需求
1.1 图片混排富文本控件 是一种图片和文字混合在一起的控件,文本之间可以插入图片,类似于网页的排版样式。 1.2 该控件主要是仿兴趣部落的效果,实现原理主要基于RecyclerView方案实现的。
Android垂直滚动的图文混排字幕效果
Android下从网络获取数据实现图文混排效果,详细可以参见博客:http://www.cnblogs.com/plokmju/p/android_ImageOrText.html
这是一个flash源文件,效果很好,测试平台为flash 8.0(如果提示问题请选择合适的版本试试),代码的效果是:图文混排效果代码
Android源码——Spinner图文混排源码_new_15.zip
Android源码——Spinner图文混排源码_new_15.7z
一个使用android图文混排的编程例子,可以自动解析一段string文字内所包含的图片
主要介绍了Android实现文字和图片混排的方法,实例分析了文字环绕图片效果的具体功能显示及页面布局实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下
android textview图文混排支持GIF图 原生方式实现 glide支持
漂亮的图片混排布局,感觉不瀑布流高大上,。
Android 原生控件实现图文混排、混编,支持编辑网络图片和本地图片,超好用。
中等职业学校计算机专业的说课课件,是word部分图文混排内容的,内容合理,结构紧凑。
使用RecyclerView实现GridView和ListView混排的效果
android 文字图片混排,在一个TextView中显示文字穿插图片,文字变色效果
android开发 自定义图文混排控件,是基于网络上一个单点触控来写的,使用见博客地址:http://www.cnblogs.com/feijian/p/4736485.html
图文混排,图片拖动。