Android网络加载图片并滚动显示

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

    android应用app离不开服务器端的数据,我们装在手机上的app应用都是通过http相关协议及方法从对应的服务器上取下来的。几乎所有的app 都少不了从网络加载图片并展示在手机上,今天我写的就是把网络图片加载到本地并用ViewPager展示出来,可以实现图片自动滚动播放,当然可以手动翻 页。借助了网络图片开源框架ImageLoader,其在github开源地址是:https://github.com/nostra13/Android-Universal-Image-Loader,如果想知道这开源框架的具体使用方法可以参考http://blog.csdn.net/wwj_748/article/details/10079311这篇博客。

   下面直接贴代码:

<?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:background="#fff0f0ed"
    android:orientation="vertical" >

        <android.support.v4.view.AutoScrollViewPager
            android:id="@+id/advertisementVp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#ffa1a1a1" />
        <LinearLayout
            android:id="@+id/advertisement_dotLl"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:gravity="center"
            android:orientation="horizontal"
            android:paddingBottom="4.5dp"
            android:paddingTop="4.5dp" >
        </LinearLayout>
</RelativeLayout><!--实际项目布局不是这样,这只是个举例-->


下面这个类是我们在实际项目中把V4包中的AutoScrollViewPager做了修改:

public class AutoScrollViewPager<T extends PagerData> extends ViewPager {
public interface OnPageItemClickListener<T extends PagerData> {
void onPageItemClickListener(T pd);
}
private int mScrollTime = 0;
private int oldIndex = 0;
private int curIndex = 0;
private List<T> mPagerData = new ArrayList<T>();
private PagerAdapter pagerAdapter;
private LinearLayout indicatorView;
private int focusedDrawable, normalDrawable;
private LayoutInflater inflater;
private OnPageItemClickListener<T> pageItemClickListener;
private boolean isFakeCycle = false;// 是否是假的循环
private boolean isStartScroll;
public AutoScrollViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
inflater = LayoutInflater.from(context);
focusedDrawable = R.drawable.common_dot_selected;
normalDrawable = R.drawable.common_dot_normal;
setInternalPageChangeListener(new OnPageChangeListener() {
public void onPageSelected(int i) {
if (mPagerData.isEmpty() || indicatorView == null || indicatorView.getChildCount() == 0)
return;
curIndex = i % mPagerData.size();
// 取消圆点选中
indicatorView.getChildAt(oldIndex).setBackgroundResource(normalDrawable);
// 圆点选中
indicatorView.getChildAt(curIndex).setBackgroundResource(focusedDrawable);
oldIndex = curIndex;
}

public void onPageScrolled(int arg0, float arg1, int arg2) {}
public void onPageScrollStateChanged(int arg0) {}

});

// 设置滑动动画时间 ,如果用默认动画时间可不用 ,反射技术实现
new FixedSpeedScroller(getContext()).setDuration(this, 700);
pagerAdapter = new MyPagerAdapter();
setAdapter(pagerAdapter);
setOffscreenPageLimit(2);
requestDisallowInterceptTouchEvent(true);
options = new DisplayImageOptions.Builder()

                                .showImageOnLoading(R.drawable.index_advert_default) //加载中显示的默认图片
.showImageForEmptyUri(R.drawable.index_advert_default) //加载错误默认图片
.showImageOnFail(R.drawable.index_advert_default)//加载错误时的默认图片
.cacheInMemory(true)// 开启内存缓存
.cacheOnDisk(true) // 开启硬盘缓存
.resetViewBeforeLoading(false).build());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (isStartScroll) {
start(mScrollTime);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (isStartScroll)
handler.removeCallbacksAndMessages(null);
}
/** 构建内部索引父view */
private void initInnerIndicator() {
indicatorView = new IndicatorView(getContext());
indicatorView.setGravity(Gravity.CENTER);
indicatorView.setBackgroundColor(0x0fFF00FF);
indicatorView.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams params = new LayoutParams();
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
params.height = 40;
params.gravity = Gravity.BOTTOM;
addView(indicatorView, params);
}
public void setDatas(List<T> imgUrls, LinearLayout outIndicator, boolean needInnerIndicator, boolean isFakeCycle) {
this.isFakeCycle = isFakeCycle;
setDatas(imgUrls, outIndicator, needInnerIndicator);
}
/**重复调用可能会anr*/
public void setDatas(List<T> imgUrls, LinearLayout outIndicator, boolean needInnerIndicator) {
if (outIndicator != null) {
indicatorView = outIndicator;
} else if (needInnerIndicator) {
initInnerIndicator();
}
mPagerData.clear();
mPagerData.addAll(imgUrls);
pagerAdapter.notifyDataSetChanged();
}
/**重新加载图片数据,刷新vp内容*/
public void refreshDatas(List<T> imgUrls, LinearLayout outIndicator, boolean needInnerIndicator, boolean isFakeCycle) {
this.isFakeCycle = isFakeCycle;
if (outIndicator != null) {
indicatorView = outIndicator;
} else if (needInnerIndicator) {
initInnerIndicator();
}
mPagerData.clear();
mPagerData.addAll(imgUrls);
pagerAdapter = new MyPagerAdapter();
setAdapter(pagerAdapter);
pagerAdapter.notifyDataSetChanged();
}
@Override
void dataSetChanged() {
super.dataSetChanged();
setUpIndicator();
}

// 设置圆点
private void setUpIndicator() {
if (indicatorView != null) {
indicatorView.removeAllViews();
if (mPagerData.isEmpty()) {
indicatorView.setVisibility(View.GONE);
return;
} else {
indicatorView.setVisibility(View.VISIBLE);
}
for (int i = 0; i < mPagerData.size(); i++) {
View v = inflater.inflate(R.layout.auto_scrollpage_dot, indicatorView, false);
v.setBackgroundResource(normalDrawable);
indicatorView.addView(v);
}
indicatorView.getChildAt(0).setBackgroundResource(focusedDrawable);
}
curIndex = oldIndex = 0;
if (mPagerData.size() > 1 && isFakeCycle) {
setCurrentItem(15 - 15 % mPagerData.size());// 设置选中为中间/图片为和第0张一样
} else {
setCurrentItem(0);
}
}
/** 获取真实的当前位置 */
public int getCurrentPosition() {
return curIndex;
}

/** 获取真实的当前位置的数据 */
public T getCurrentData() throws IndexOutOfBoundsException {
return mPagerData.get(curIndex);
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) {
start();
} else {
handler.removeCallbacksAndMessages(null);
}
return super.onInterceptTouchEvent(ev);
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) {
start();
} else {
handler.removeCallbacksAndMessages(null);
}
return super.onTouchEvent(ev);
}

/** 开始广告滚动 */
private void start() {
start(mScrollTime);
}
public void start(int scrollTime) {
// handler.removeCallbacksAndMessages(null);
mScrollTime = scrollTime;
isStartScroll = false;
if (mScrollTime > 0 && !mPagerData.isEmpty()) {
isStartScroll = true;
handler.sendMessageDelayed(handler.obtainMessage(), mScrollTime);
}
}
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
handler.removeCallbacksAndMessages(null);
if (isFakeCycle) {
setCurrentItem(getCurrentItem() + 1);
} else {
if (getCurrentItem() == mPagerData.size() - 1) {
setCurrentItem(0, true);
} else {
setCurrentItem(getCurrentItem() + 1);
}
}
handler.sendMessageDelayed(handler.obtainMessage(), mScrollTime);
};
};
private DisplayImageOptions options;
public void setImageOptions(DisplayImageOptions options) {
this.options = options;
}
// 适配器 //循环设置
private class MyPagerAdapter extends PagerAdapter {

@Override
public int getCount() {
if (mPagerData.size() == 1) {
return 1;
} else if (mPagerData.size() > 1) { return isFakeCycle ? Integer.MAX_VALUE : mPagerData.size(); }
return 0;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
final int realP = position % mPagerData.size();
final ImageView netImgView = (ImageView) inflater.inflate(R.layout.auto_scrollpage_img, container, false);
ImageLoader.getInstance().displayImage(mPagerData.get(realP).getImageUrl(), netImgView, options);
netImgView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (pageItemClickListener != null) {
pageItemClickListener.onPageItemClickListener(mPagerData.get(realP));
}
}
});
container.addView(netImgView);
return netImgView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (object instanceof View) {
container.removeView((View) object);
}
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
/** 设置显示条目的点击事件 */
public void setOnPageItemClickListener(OnPageItemClickListener<T> pageItemClickListener) {
this.pageItemClickListener = pageItemClickListener;
}
}


是个接口,主要实现取得图片的url:

public interface PagerData{
public String getImageUrl();//用于显示网络图片
public void setImageUrl(String imgUrl);
}



有了以上的准备,只需要在Activity中取得图片的url地址,调用refreshDatas()方法把参数传入就可以了,activity中关键代码:

viewPager = (AutoScrollViewPager<AdvertisementInfo>) headerView.findViewById(R.id.viewPager );//获取ViewPager对象,

                advertisementVp.refreshDatas();//传入对应参数
        advertisementVp.start(3000);


ok啦,时间原因,没有贴出所有代码,仅供参考。

标签: isp 代码 服务器 服务器端 网络

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Android开发中apk安装包常用工具

下一篇:Android开发中常用字符处理工具类