首页 » 技术分享 » 利用AbSlidingPlayView做一个广告轮播效果

利用AbSlidingPlayView做一个广告轮播效果

 

AbSlidingPlayView是AndBase框架中的功能之一,今天就来尝试用AbSlidingPlayView来做一个好多类新闻app都会涉及到的,广播轮播效果,能和viewpager一样实现滑动,并且带有各种监听事件

下面先贴出AbSlidingPlayView类的源码,基本只要复制黏贴到项目中去即可

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import java.util.ArrayList;
import java.util.List;

import com.example.text.R;


public class AbSlidingPlayView extends LinearLayout {

    /** The tag. */
    private static String TAG = "AbSlidingPlayView";

    /** The Constant D. */
    // private static final boolean D = AbAppData.DEBUG;

    /** The context. */
    private Context context;

    /** The m view pager. */
    private AbInnerViewPager mViewPager;

    /** The page line layout. */
    private LinearLayout pageLineLayout;

    /** The layout params pageLine. */
    public LayoutParams pageLineLayoutParams = null;

    /** The i. */
    private int count, position;

    /** The hide image. */
    private Bitmap displayImage, hideImage;

    /** The m on item click listener. */
    private AbOnItemClickListener mOnItemClickListener;

    /** The m ab change listener. */
    private AbOnChangeListener mAbChangeListener;

    /** The m ab scrolled listener. */
    private AbOnScrollListener mAbScrolledListener;

    /** The m ab touched listener. */
    private AbOnTouchListener mAbOnTouchListener;

    /** The layout params ff. */
    public LayoutParams layoutParamsFF = null;

    /** The layout params fw. */
    public LayoutParams layoutParamsFW = null;

    /** The layout params wf. */
    public LayoutParams layoutParamsWF = null;

    /** The m list views. */
    private ArrayList<View> mListViews = null;

    /** The m ab view pager adapter. */
    private AbViewPagerAdapter mAbViewPagerAdapter = null;

    /** 导航的点父View */
    private LinearLayout mPageLineLayoutParent = null;

    /** The page line horizontal gravity. */
    private int pageLineHorizontalGravity = Gravity.RIGHT;

    /** 播放的方�?*/
    private int playingDirection = 0;

    /** 播放的开�?*/
    public static boolean play = false;

    private boolean isNotRefresh = true;


    /**
     * 创建�?��AbSlidingPlayView
     * 
     * @param context
     */
    public AbSlidingPlayView(Context context) {
        super(context);
        initView(context);
    }

    /**
     * 从xml初始化的AbSlidingPlayView
     * 
     * @param context
     *            the context
     * @param attrs
     *            the attrs
     */
    public AbSlidingPlayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    /**
     * 
     * 描述:初始化这个View
     * 
     * @param context
     * @throws
     */
    public void initView(Context context) {
        this.context = context;
        layoutParamsFF = new LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        layoutParamsFW = new LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        layoutParamsWF = new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
        pageLineLayoutParams = new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        this.setOrientation(LinearLayout.VERTICAL);
        this.setBackgroundColor(Color.rgb(255, 255, 255));

        RelativeLayout mRelativeLayout = new RelativeLayout(context);

        mViewPager = new AbInnerViewPager(context);
        // 手动创建的ViewPager,如果用fragment必须调用setId()方法设置�?��id

//      mViewPager.setId(1985); as 会 warning
        mViewPager.setId(R.id.my_view);

        // 导航的点
        mPageLineLayoutParent = new LinearLayout(context);
        mPageLineLayoutParent.setPadding(0, 5, 0, 5);
        pageLineLayout = new LinearLayout(context);
        pageLineLayout.setPadding(15, 1, 15, 1);
        pageLineLayout.setVisibility(View.INVISIBLE);
        mPageLineLayoutParent.addView(pageLineLayout,
                new LayoutParams(LayoutParams.MATCH_PARENT,
                        LayoutParams.WRAP_CONTENT));
        RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        lp1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        lp1.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        lp1.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
        mRelativeLayout.addView(mViewPager, lp1);

        displayImage = UtilBitmap.getBitmapFromRes(getResources(), R.drawable.circle_point_selected);
        hideImage = UtilBitmap.getBitmapFromRes(getResources(), R.drawable.circle_point_normal);

        RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        lp2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        mRelativeLayout.addView(mPageLineLayoutParent, lp2);
        addView(mRelativeLayout, layoutParamsFW);
        mListViews = new ArrayList<View>();
        mAbViewPagerAdapter = new AbViewPagerAdapter(context, mListViews);
        mViewPager.setAdapter(mAbViewPagerAdapter);
        mViewPager.setFadingEdgeLength(0);
        mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                makesurePosition();
                onPageSelectedCallBack(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }

            @Override
            public void onPageScrolled(int position, float positionOffset,
                    int positionOffsetPixels) {
                onPageScrolledCallBack(position);
            }

        });

        mViewPager.setOnSingleTouchListener(new AbInnerViewPager.OnSingleTouchListener()
        {

            @Override
            public void onSingleTouch(int position)
            {
                mOnItemClickListener.onClick(position);
            }
        });

    }

    /**
     * 创建导航�?
     */
    public void creatIndex() {
        // 显示下面的点
        pageLineLayout.removeAllViews();
        mPageLineLayoutParent.setHorizontalGravity(pageLineHorizontalGravity);

        //pageLineLayout.setGravity(Gravity.CENTER);
//      pageLineLayout.setGravity(Gravity.RIGHT);
        pageLineLayout.setGravity(pageLineHorizontalGravity);

        pageLineLayout.setVisibility(View.VISIBLE);
        count = mListViews.size();
        for (int j = 0; j < count; j++) {
            ImageView imageView = new ImageView(context);
            pageLineLayoutParams.setMargins(5, 5, 5, 5);
            imageView.setLayoutParams(pageLineLayoutParams);
            if (j == 0) {
                //imageView.setImageResource(R.drawable.biz_fb_no_read);
                imageView.setImageBitmap(displayImage);
            } else {
                //imageView.setImageResource(R.drawable.biz_fb_read1);
                imageView.setImageBitmap(hideImage);
            }
            pageLineLayout.addView(imageView, j);
        }
    }

    /**
     * 定位点的位置.
     */
    public void makesurePosition() {
        position = mViewPager.getCurrentItem();
        for (int j = 0; j < count; j++) {
            if (position == j) {
                //((ImageView) pageLineLayout.getChildAt(position)).setImageResource(R.drawable.biz_fb_no_read);
                ((ImageView) pageLineLayout.getChildAt(position)).setImageBitmap(displayImage);
            } else {
                //((ImageView) pageLineLayout.getChildAt(j)).setImageResource(R.drawable.biz_fb_read1);
                ((ImageView) pageLineLayout.getChildAt(j)).setImageBitmap(hideImage);
            }
        }
    }

    /**
     * 描述:添加可播放视图.
     * 
     * @param view
     *            the view
     */
    public void addView(View view) {
        mListViews.add(view);
        if (view instanceof AbsListView) {
        } else {
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (mOnItemClickListener != null) 
                    {
                    }
                }
            });
            view.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View view, MotionEvent event) {
                    if (mAbOnTouchListener != null) {
                        mAbOnTouchListener.onTouch(event);
                    }
                    return false;
                }
            });
        }

        mAbViewPagerAdapter.notifyDataSetChanged();
        creatIndex();
    }

    /**
     * 描述:添加可播放视图列表.
     * 
     * @param views
     *            the views
     */
    public void addViews(List<View> views) {
        mListViews.addAll(views);
        for (View view : views) {
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onClick(position);
                    }
                }
            });

            view.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View view, MotionEvent event) {
                    if (mAbOnTouchListener != null) {
                        mAbOnTouchListener.onTouch(event);
                    }
                    return false;
                }
            });
        }
        mAbViewPagerAdapter.notifyDataSetChanged();
        creatIndex();
    }

    /**
     * 描述:删除可播放视图.
     * 
     */
    @Override
    public void removeAllViews() {
        mListViews.clear();
        mAbViewPagerAdapter.notifyDataSetChanged();
        creatIndex();
    }

    /**
     * 描述:设置页面切换事�?
     * 
     * @param position
     *            the position
     */
    private void onPageScrolledCallBack(int position) {
        if (mAbScrolledListener != null) {
            mAbScrolledListener.onScroll(position);
        }

    }

    /**
     * 描述:设置页面切换事�?
     * 
     * @param position
     *            the position
     */
    private void onPageSelectedCallBack(int position) {
        if (mAbChangeListener != null) {
            mAbChangeListener.onChange(position);
        }

    }

    /** 用与轮换�?handler. 正反方向 0-x , x-0*/

    /*private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                int count = mListViews.size();
                int i = mViewPager.getCurrentItem();
                if (playingDirection == 0) {
                    if (i == count - 1) {
                        playingDirection = -1;
                        i--;
                    } else {
                        i++;
                    }
                } else {
                    if (i == 0) {
                        playingDirection = 0;
                        i++;
                    } else {
                        i--;
                    }
                }

                mViewPager.setCurrentItem(i);
                if (play) {
                    handler.postDelayed(runnable, 3000);
                }
            }
        }

    };*/

    /** 用与轮换的 handler. 0-x,0-x ... 循环*/
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            if (msg.what==0) {
                int count = mListViews.size();
                int i = mViewPager.getCurrentItem();
                if(playingDirection==0){
                    if(i == count-1){
                        playingDirection = -1;
                        i=0;
                    }else{
                        i++;
                    }
                }else{
                    if(i == 0){
                        playingDirection = 0;
                        i++;
                    }else{
                        i=0;
                    }
                }


                mViewPager.setCurrentItem(i, true);
                if(play){
                    //控制广告图几秒钟换一次
                    handler.postDelayed(runnable, 5000);
                }
            }
        }

    };

    /** 用于轮播的线�? */
    private Runnable runnable = new Runnable() {
        public void run() {
            if (mViewPager != null) {
                handler.sendEmptyMessage(0);
            }
        }
    };


    private boolean isNotFirstPlay = true;

    /**
     * 描述:自动轮�?
     */
    public void startPlay() 
    {
        play = true;
        if(isNotFirstPlay)
        {
            if (handler != null)
            {
                handler.postDelayed(runnable, 5000);
            }
        //  isNotFirstPlay = false;
        }
    }

    /**
     * 描述:自动轮�?
     */
    public void stopPlay() {
        if (handler != null) {
            play = false;
            handler.removeCallbacks(runnable);
        }
    }

    /**
     * 设置点击事件监听.
     * 
     * @param onItemClickListener
     *            the new on item click listener
     */
    public void setOnItemClickListener(AbOnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    /**
     * 描述:设置页面切换的监听�?
     * 
     * @param abChangeListener
     *            the new on page change listener
     */
    public void setOnPageChangeListener(AbOnChangeListener abChangeListener) {
        mAbChangeListener = abChangeListener;
    }

    /**
     * 描述:设置页面滑动的监听�?
     * 
     * @param abScrolledListener
     *            the new on page scrolled listener
     */
    public void setOnPageScrolledListener(AbOnScrollListener abScrolledListener) {
        mAbScrolledListener = abScrolledListener;
    }

    /**
     * 
     * 描述:设置页面Touch的监听器.
     * 
     * @param abOnTouchListener
     * @throws
     */
    public void setOnTouchListener(AbOnTouchListener abOnTouchListener) {
        mAbOnTouchListener = abOnTouchListener;
    }

    /**
     * Sets the page line image.
     * 
     * @param displayImage
     *            the display image
     * @param hideImage
     *            the hide image
     */
    public void setPageLineImage(Bitmap displayImage, Bitmap hideImage) {
        this.displayImage = displayImage;
        this.hideImage = hideImage;
        creatIndex();

    }

    /**
     * 描述:获取这个滑动的ViewPager�?
     * 
     * @return the view pager
     */
    public ViewPager getViewPager() {
        return mViewPager;
    }

    /**
     * 描述:获取当前的View的数�?
     * 
     * @return the count
     */
    public int getCount() {
        return mListViews.size();
    }

    /**
     * 描述:设置页显示条的位置,在AddView前设�?
     * 
     * @param horizontalGravity
     *            the new page line horizontal gravity
     */
    public void setPageLineHorizontalGravity(int horizontalGravity) {
        pageLineHorizontalGravity = horizontalGravity;
    }

    /**
     * 如果外层有ScrollView�?��设置.
     * 
     * @param parentScrollView
     *            the new parent scroll view
     */
    public void setParentScrollView(ScrollView parentScrollView) {
        this.mViewPager.setParentScrollView(parentScrollView);
    }

    /**
     * 如果外层有ListView�?��设置.
     * 
     * @param parentListView
     *            the new parent list view
     */
    public void setParentListView(ListView parentListView) {
        this.mViewPager.setParentListView(parentListView);
    }

    /**
     * 
     * 描述:设置导航点的背�?  * 
     * @param resid
     * @throws
     */
    public void setPageLineLayoutBackground(int resid) {
        pageLineLayout.setBackgroundResource(resid);
    }


    public AbInnerViewPager getAbViewPager()
    {
        return mViewPager;
    }


}

代码很长,里面有各种注释,就不多说了,可以仔细研究一下里面的源码,可以对轮播效果进行各种控制,比如翻页的快慢,翻页的时长等等

在这里还需要用到一些其他的接口类,这里就不贴出来了,后面会贴出demo的下载地址,

接下来我们写一个布局文件,很简单,直接上代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


    <com.example.utils.AbSlidingPlayView 
        android:id="@+id/mAbSlidingPlayView"
        android:layout_width="match_parent"
        android:layout_height="150dp">

    </com.example.utils.AbSlidingPlayView>


</RelativeLayout>

就只有一个自定义的控件。
接下来上主Activity的代码:

import java.util.ArrayList;
import com.example.utils.AbOnChangeListener;
import com.example.utils.AbOnItemClickListener;
import com.example.utils.AbSlidingPlayView;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

        public class TextActivity extends Activity{
            private AbSlidingPlayView mSlidingPlayView;
            private Context mContext;

            private ArrayList<Integer> list;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                // TODO Auto-generated method stub
                super.onCreate(savedInstanceState);
                setContentView(R.layout.textac);
                mContext=this;
                list=new ArrayList<Integer>();
                //先来一个测试的arrayList,给他添加一些图片进去
                list.add(R.drawable.girl);
                list.add(R.drawable.shibai);
                list.add(R.drawable.shibai);

                mSlidingPlayView=(AbSlidingPlayView) findViewById(R.id.mAbSlidingPlayView);
                mSlidingPlayView.setPageLineHorizontalGravity(Gravity.RIGHT);
                //mSlidingPlayView的点击事件
                mSlidingPlayView.setOnItemClickListener(new AbOnItemClickListener() {
                    @Override
                    public void onClick(int position) {
                        mSlidingPlayView.setOverScrollMode(View.OVER_SCROLL_ALWAYS);
                        mSlidingPlayView.clearChildFocus(mSlidingPlayView.getFocusedChild());


                    }
                });
                //mSlidingPlayView的滑动的监听事件 
                mSlidingPlayView.setOnPageChangeListener(new AbOnChangeListener() {
                    @Override
                    public void onChange(int position) {

                    }
                });
                //对list进行循环
               for(int i=0;i<list.size();i++){
                   final View playView = LayoutInflater.from(mContext).inflate(R.layout.play_view_item, null);
                ImageView playImage =
                        (ImageView) playView.findViewById(R.id.mPlayImage);
                playImage.setImageResource(list.get(i));
                //最后把playView添加到mSlidingPlayView里面去
                mSlidingPlayView.addView(playView);
               }

            }
            @Override
            protected void onResume() {
                // TODO Auto-generated method stub
                super.onResume();
                //mSlidingPlayView开始循环播放
                mSlidingPlayView.startPlay();
            }

            @Override
            protected void onStop() {
                // TODO Auto-generated method stub
                super.onStop();
                //mSlidingPlayView结束循环播放
                mSlidingPlayView.stopPlay();
            }
    }

里面有各种接口和监听事件,是不是很简单!

最后上效果图:
这是最后程序运行出来的效果图

最后献上demo的下载地址,有兴趣可以下载一下:
http://download.csdn.net/detail/u014605700/9585510

转载自原文链接, 如需删除请联系管理员。

原文链接:利用AbSlidingPlayView做一个广告轮播效果,转载请注明来源!

0