android 自定义gallerey并实现预览功能

自从Gallery被谷歌废弃以后,Google推荐使用ViewPager和HorizontalScrollView来实现Gallery的效果。的确HorizontalScrollView可以实现Gallery的效果,但是HorizontalScrollView存在一个很大的问题,如果你仅是用来展示少量的图片,应该是没问题的,但是如果我希望HorizontalScrollView可以想ViewPager一样,既可以绑定数据集(动态改变图片),还能做到,不管多少图片都不会OOM(ViewPager内部一直初始化,回收,至多只保持3个View)。本篇博客首先介绍HorizontalScrollView的简单用法,然后会在此基础上进行扩展,自定义HorizontalScrollView实现我们上面提到的效果,类似一屏可以显示多个View的ViewPager,再多的图片也不怕OOM。

首先差一张图片

自定义HorizontalScrollView

思想:

1、首先根据屏幕的大小和Item的大小,计算可以一个屏幕最多可以加载多少个Item,然后加载该数量Item。

2、当用户右滑(从右向左),滑动到一定距离时,加载下一张,删除第一张

3、当用户左滑(从左向右),滑动到一定距离时,加载上一张,删除最后一张

public class MyHorizontalScrollView extends HorizontalScrollView implements
        OnClickListener {

    private CurrentImageChangeListener mListener;
    private OnItemClickListener mOnClickListener;
    private LinearLayout mContainer;
    private int mChildWidth;
    private int mChildHeight;
    private int mCurrentIndex;
    private int mFristIndex;
    private HorizontalScrollViewAdapter mAdapter;
    private int mCountOneScreen;
    private int mScreenWitdh;
    private Map<View, Integer> mViewPos = new HashMap<View, Integer>();


    public MyHorizontalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        mScreenWitdh = outMetrics.widthPixels;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mContainer = (LinearLayout) getChildAt(0);
    }

    protected void loadNextImg() {
        if (mCurrentIndex == mAdapter.getCount() - 1) {
            return;
        }
        scrollTo(0, 0);
        mViewPos.remove(mContainer.getChildAt(0));
        mContainer.removeViewAt(0);
        View view = mAdapter.getView(++mCurrentIndex, null, mContainer);
        view.setOnClickListener(this);
        mContainer.addView(view);
        mViewPos.put(view, mCurrentIndex);
        mFristIndex++;
        if (mListener != null) {
            notifyCurrentImgChanged();
        }

    }

    protected void loadPreImg() {
        if (mFristIndex == 0)
            return;
        int index = mCurrentIndex - mCountOneScreen;
        if (index >= 0) {
            int oldViewPos = mContainer.getChildCount() - 1;
            mViewPos.remove(mContainer.getChildAt(oldViewPos));
            mContainer.removeViewAt(oldViewPos);
            //将此View放入第一个位置
            View view = mAdapter.getView(index, null, mContainer);
            mViewPos.put(view, index);
            mContainer.addView(view, 0);
            view.setOnClickListener(this);
            //水平滚动位置向左移动view的宽度个像素
            scrollTo(mChildWidth, 0);
            //当前位置--,当前第一个显示的下标--
            mCurrentIndex--;
            mFristIndex--;
            if (mListener != null) {
                notifyCurrentImgChanged();

            }
        }
    }

    //更改当前背景色
    public void notifyCurrentImgChanged() {
        for (int i = 0; i < mContainer.getChildCount(); i++) {
            mContainer.getChildAt(i).setBackgroundColor(Color.WHITE);
        }
        mListener.onCurrentImgChanged(mFristIndex, mContainer.getChildAt(0));
    }

    public void setDatas(HorizontalScrollViewAdapter mAdapter) {
        this.mAdapter = mAdapter;
        mContainer = (LinearLayout) getChildAt(0);
        final View view = mAdapter.getView(0, null, mContainer);
        mContainer.addView(view);
        if (mChildWidth == 0 && mChildHeight == 0) {
            int w = MeasureSpec.makeMeasureSpec(0,
                    MeasureSpec.UNSPECIFIED);
            int h = MeasureSpec.makeMeasureSpec(0,
                    MeasureSpec.UNSPECIFIED);
            view.measure(w, h);
            mChildHeight = view.getMeasuredHeight();
            mChildWidth = view.getMeasuredWidth();
            mChildHeight = view.getMeasuredHeight();
            mCountOneScreen = (mScreenWitdh / mChildWidth == 0) ? mScreenWitdh / mChildWidth + 1 : mScreenWitdh / mChildWidth + 2;
        }
        initFirstScreenChildren(mCountOneScreen);
    }

    public void initFirstScreenChildren(int mCountOneScreen) {
        mContainer = (LinearLayout) getChildAt(0);
        mContainer.removeAllViews();
        mViewPos.clear();

        for (int i = 0; i < mCountOneScreen; i++) {
            View view = mAdapter.getView(i, null, mContainer);
            view.setOnClickListener(this);
            mContainer.addView(view);
            mViewPos.put(view, i);
            mCurrentIndex = i;
        }
        if (mListener != null) {
            notifyCurrentImgChanged();
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_MOVE:
                int scrollX = getScrollX();
                // 如果当前scrollX为view的宽度,加载下一张,移除第一张
                if (scrollX >= mChildWidth) {
                    loadNextImg();
                }
                // 如果当前scrollX = 0, 往前设置一张,移除最后一张
                if (scrollX == 0) {
                    loadPreImg();
                }
                break;
        }
        return super.onTouchEvent(ev);
    }

    @Override
    public void onClick(View v) {
        if (mOnClickListener != null) {
            for (int i = 0; i < mContainer.getChildCount(); i++) {
                mContainer.getChildAt(i).setBackgroundColor(Color.WHITE);
            }
            mOnClickListener.onClick(v, mViewPos.get(v));
        }
    }

    public void setOnItemClickListener(OnItemClickListener mOnClickListener) {
        this.mOnClickListener = mOnClickListener;
    }

    public void setCurrentImageChangeListener(
            CurrentImageChangeListener mListener) {
        this.mListener = mListener;
    }


    public interface CurrentImageChangeListener {
        void onCurrentImgChanged(int position, View viewIndicator);
    }

    public interface OnItemClickListener {
        void onClick(View view, int pos);
    }
}

接下来我们写一个Adapter用来填充界面,然后在我们首页组装下数据,设置下适配器就好了,是不是很简单。

public class HorizontalScrollViewAdapter extends BaseAdapter{

    private Context mContext;
    private LayoutInflater mInflater;
    private List<GalleryModel> mDatas;

    public HorizontalScrollViewAdapter(Context context, List<GalleryModel> mDatas) {
        this.mContext = context;
        mInflater = LayoutInflater.from(context);
        this.mDatas = mDatas;
    }

    public int getCount() {
        return mDatas.size();
    }

    public Object getItem(int position) {
        return mDatas.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null) {
            convertView = mInflater.inflate(
                    R.layout.activity_gallery_item, parent, false);
            viewHolder = new ViewHolder(convertView);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        initItem(viewHolder,position);
        return convertView;
    }

    private void initItem(ViewHolder viewHolder, int position) {
        viewHolder.itemImage.setImageResource(mDatas.get(position).image);
        viewHolder.itemText.setText(mDatas.get(position).name);
    }

     class ViewHolder {
        @Bind(R.id.item_image)
        ImageView itemImage;
        @Bind(R.id.item_text)
        TextView itemText;

        public ViewHolder(View parent) {
            ButterKnife.bind(this, parent);
            parent.setTag(this);
        }
    }

}

有兴趣的可以下载代码:

https://github.com/xiangzhihong/gallery

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区

领取腾讯云代金券