本文主要是介绍安卓中实现动态轮播图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.学习此文章之前请先学习
Android高级图片滚动控件,编写3D版的图片轮播器_guolin的博客-CSDN博客_android 轮播图3d
本文主要是介绍如何实现动态的轮播图,主要是基于上一篇文章的获取网络图片,从而实现动态的轮播图。传统轮播图是使用本地固定的几张图片进行轮播,现在实现的是从网络上获取图片进行3D轮播展示效果。
实现了三种触发获取图片的事件,一种是点击按钮进行更新图片,一种是进行向左滑动获取图片,一种是按键获取图片。
2.项目结构
项目结构比较简单,一个mainactivity和两个文件进行辅助,还有一个xml文件进行布局。
3.activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#ffaa3f" ><com.qiri.myapplication.Image3DSwitchViewandroid:id="@+id/image_switch_view"android:layout_width="match_parent"android:layout_height="300dp"android:layout_marginTop="100dp"><com.qiri.myapplication.Image3DViewandroid:id="@+id/image1"android:layout_width="match_parent"android:layout_height="match_parent"android:scaleType="fitXY"android:src="@drawable/t1" /><com.qiri.myapplication.Image3DViewandroid:id="@+id/image2"android:layout_width="match_parent"android:layout_height="match_parent"android:scaleType="fitXY"android:src="@drawable/t2" /><com.qiri.myapplication.Image3DViewandroid:id="@+id/image3"android:layout_width="match_parent"android:layout_height="match_parent"android:scaleType="fitXY"android:src="@drawable/t3" /><com.qiri.myapplication.Image3DViewandroid:id="@+id/image4"android:layout_width="match_parent"android:layout_height="match_parent"android:scaleType="fitXY"android:src="@drawable/t4" /><com.qiri.myapplication.Image3DViewandroid:id="@+id/image5"android:layout_width="match_parent"android:layout_height="match_parent"android:scaleType="fitXY"android:src="@drawable/t5" /><com.qiri.myapplication.Image3DViewandroid:id="@+id/image6"android:layout_width="match_parent"android:layout_height="match_parent"android:scaleType="fitXY"android:src="@drawable/t1" /><com.qiri.myapplication.Image3DViewandroid:id="@+id/image7"android:layout_width="match_parent"android:layout_height="match_parent"android:scaleType="fitXY"android:src="@drawable/t2" /></com.qiri.myapplication.Image3DSwitchView><Buttonandroid:id="@+id/btn"android:text="1/7"android:textSize="32dp"android:textColor="#ffffff"android:layout_below="@+id/image_switch_view"android:background="#fadd44"android:layout_width="200dp"android:layout_height="100dp"android:layout_marginLeft="350dp"/><Buttonandroid:layout_width="200dp"android:layout_height="100dp"android:id="@+id/btn2"android:hint="点击更换图片"android:background="@color/fastlane_background"android:layout_below="@+id/image_switch_view"android:layout_marginLeft="620dp"/>
</RelativeLayout>
效果
这里主要是设置了七个图片,还有一个索引展示是第几张图片,还有一个点击按钮。
在drawable中存放了最开始的几张图片,这样程序刚运行的时候会进行加载。
4.colors.xml
<resources><color name="background_gradient_start">#000000</color><color name="background_gradient_end">#DDDDDD</color><color name="fastlane_background">#0096a6</color><color name="search_opaque">#ffaa3f</color><color name="selected_background">#ffaa3f</color><color name="default_background">#3d3d3d</color>
</resources>
这个文件是放一些颜色布局,没有可能会报错,但是很好解决。
5.Image3DView
public class Image3DView extends ImageView {/*** 旋转角度的基准值*/private static final float BASE_DEGREE = 50f;/*** 旋转深度的基准值*/private static final float BASE_DEEP = 150f;private Camera mCamera;private Matrix mMaxtrix;private Bitmap mBitmap;/*** 当前图片对应的下标*/private int mIndex;/*** 在前图片在X轴方向滚动的距离*/private int mScrollX;/*** Image3DSwitchView控件的宽度*/private int mLayoutWidth;/*** 当前图片的宽度*/private int mWidth;/*** 当前旋转的角度*/private float mRotateDegree;/*** 旋转的中心点*/private float mDx;/*** 旋转的深度*/private float mDeep;public Image3DView(Context context, AttributeSet attrs) {super(context, attrs);mCamera = new Camera();mMaxtrix = new Matrix();//设置可获焦 & 可点击setFocusable(true);setClickable(true);}/*** 初始化Image3DView所需要的信息,包括图片宽度,截取背景图等。*/public void initImageViewBitmap() {if (mBitmap == null) {//我们要获取cache首先要通过setDrawingCacheEnable方法开启cache,然后再调用getDrawingCache方法就可以获得view的cache图片了。setDrawingCacheEnabled(true);buildDrawingCache();mBitmap = getDrawingCache();}mLayoutWidth = Image3DSwitchView.mWidth;mWidth = getWidth() + Image3DSwitchView.IMAGE_PADDING * 2;}/*** 设置旋转角度。** @param index 当前图片的下标* @param scrollX 当前图片在X轴方向滚动的距离*/public void setRotateData(int index, int scrollX) {mIndex = index;mScrollX = scrollX;}/*** 回收当前的Bitmap对象,以释放内存。*/public void recycleBitmap() {if (mBitmap != null && !mBitmap.isRecycled()) {mBitmap.recycle();}}@Overridepublic void setImageResource(int resId) {super.setImageResource(resId);mBitmap = null;initImageViewBitmap();}@Overridepublic void setImageBitmap(Bitmap bm) {super.setImageBitmap(bm);mBitmap = null;initImageViewBitmap();}@Overridepublic void setImageDrawable(Drawable drawable) {super.setImageDrawable(drawable);mBitmap = null;initImageViewBitmap();}@Overridepublic void setImageURI(Uri uri) {super.setImageURI(uri);//mBitmap = null;initImageViewBitmap();}@Overrideprotected void onDraw(Canvas canvas) {if (mBitmap == null) {// 如果Bitmap对象还不存在,先使用父类的onDraw方法进行绘制super.onDraw(canvas);} else {if (isImageVisible()) {// 绘图时需要注意,只有当图片可见的时候才进行绘制,这样可以节省运算效率computeRotateData();mCamera.save();mCamera.translate(0.0f, 0.0f, mDeep);mCamera.rotateY(mRotateDegree);mCamera.getMatrix(mMaxtrix);mCamera.restore();mMaxtrix.preTranslate(-mDx, -getHeight() / 2);mMaxtrix.postTranslate(mDx, getHeight() / 2);canvas.drawBitmap(mBitmap, mMaxtrix, null);}}}/*** 在这里计算所有旋转所需要的数据。*/private void computeRotateData() {float degreePerPix = BASE_DEGREE / mWidth;float deepPerPix = BASE_DEEP / ((mLayoutWidth - mWidth) / 2);switch (mIndex) {case 0:mDx = mWidth;mRotateDegree = 360f - (2 * mWidth + mScrollX) * degreePerPix;if (mScrollX < -mWidth) {mDeep = 0;} else {mDeep = (mWidth + mScrollX) * deepPerPix;}break;case 1:if (mScrollX > 0) {mDx = mWidth;mRotateDegree = (360f - BASE_DEGREE) - mScrollX * degreePerPix;mDeep = mScrollX * deepPerPix;} else {if (mScrollX < -mWidth) {mDx = -Image3DSwitchView.IMAGE_PADDING * 2;mRotateDegree = (-mScrollX - mWidth) * degreePerPix;} else {mDx = mWidth;mRotateDegree = 360f - (mWidth + mScrollX) * degreePerPix;}mDeep = 0;}break;case 2:if (mScrollX > 0) {mDx = mWidth;mRotateDegree = 360f - mScrollX * degreePerPix;mDeep = 0;if (mScrollX > mWidth) {mDeep = (mScrollX - mWidth) * deepPerPix;}} else {mDx = -Image3DSwitchView.IMAGE_PADDING * 2;mRotateDegree = -mScrollX * degreePerPix;mDeep = 0;if (mScrollX < -mWidth) {mDeep = -(mWidth + mScrollX) * deepPerPix;}}break;case 3:if (mScrollX < 0) {mDx = -Image3DSwitchView.IMAGE_PADDING * 2;mRotateDegree = BASE_DEGREE - mScrollX * degreePerPix;mDeep = -mScrollX * deepPerPix;} else {if (mScrollX > mWidth) {mDx = mWidth;mRotateDegree = 360f - (mScrollX - mWidth) * degreePerPix;} else {mDx = -Image3DSwitchView.IMAGE_PADDING * 2;mRotateDegree = BASE_DEGREE - mScrollX * degreePerPix;}mDeep = 0;}break;case 4:mDx = -Image3DSwitchView.IMAGE_PADDING * 2;mRotateDegree = (2 * mWidth - mScrollX) * degreePerPix;if (mScrollX > mWidth) {mDeep = 0;} else {mDeep = (mWidth - mScrollX) * deepPerPix;}break;}}/*** 判断当前图片是否可见。** @return 当前图片可见返回true,不可见返回false。*/private boolean isImageVisible() {boolean isVisible = false;switch (mIndex) {case 0:if (mScrollX < (mLayoutWidth - mWidth) / 2 - mWidth) {isVisible = true;} else {isVisible = false;}break;case 1:if (mScrollX > (mLayoutWidth - mWidth) / 2) {isVisible = false;} else {isVisible = true;}break;case 2:if (mScrollX > mLayoutWidth / 2 + mWidth / 2|| mScrollX < -mLayoutWidth / 2 - mWidth / 2) {isVisible = false;} else {isVisible = true;}break;case 3:if (mScrollX < -(mLayoutWidth - mWidth) / 2) {isVisible = false;} else {isVisible = true;}break;case 4:if (mScrollX > mWidth - (mLayoutWidth - mWidth) / 2) {isVisible = true;} else {isVisible = false;}break;}return isVisible;}}
6.Image3DSwitchView
public class Image3DSwitchView extends LinearLayout {private int currentPage =0;//定义当前第几页/*** 图片左右两边的空白间距*/public static final int IMAGE_PADDING = 5;private static final int TOUCH_STATE_REST = 0;private static final int TOUCH_STATE_SCROLLING = 1;/*** 滚动到下一张图片的速度*/private static final int SNAP_VELOCITY = 600;/*** 表示滚动到下一张图片这个动作*/private static final int SCROLL_NEXT = 0;/*** 表示滚动到上一张图片这个动作*/private static final int SCROLL_PREVIOUS = 1;/*** 表示滚动回原图片这个动作*/private static final int SCROLL_BACK = 2;private static Handler handler = new Handler();/*** 控件宽度*/public static int mWidth;private VelocityTracker mVelocityTracker;//主要用跟踪触摸屏事件(flinging事件和其他gestures手势事件)的速率private Scroller mScroller;/*** 图片滚动监听器,当图片发生滚动时回调这个接口*/private OnImageSwitchListener mListener;/*** 记录当前的触摸状态*/private int mTouchState = TOUCH_STATE_REST;/*** 记录被判定为滚动运动的最小滚动值*/private int mTouchSlop;/*** 记录控件高度*/private int mHeight;/*** 记录每张图片的宽度*/private int mImageWidth;/*** 记录图片的总数量*/private int mCount;/*** 记录当前显示图片的坐标*/private int mCurrentImage;public int getmCurrentImage() {return mCurrentImage;}public void setmCurrentImage(int mCurrentImage) {this.mCurrentImage = mCurrentImage;}/*** 记录上次触摸的横坐标值*/private float mLastMotionX;/*** 是否强制重新布局*/private boolean forceToRelayout;private int[] mItems;public Image3DSwitchView(Context context, AttributeSet attrs) {super(context, attrs);mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();mScroller = new Scroller(context);//设置可以获得焦点setFocusable(true);}@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) {if (changed || forceToRelayout) {mCount = getChildCount();// 图片数量必须大于5,不然无法正常显示if (mCount < 5) {return;}mWidth = getMeasuredWidth();mHeight = getMeasuredHeight();// 每张图片的宽度设定为控件宽度的百分之六十mImageWidth = (int) (mWidth * 0.6);if (mCurrentImage >= 0 && mCurrentImage < mCount) {mScroller.abortAnimation();setScrollX(0);int left = -mImageWidth * 2 + (mWidth - mImageWidth) / 2;// 分别获取每个位置上应该显示的图片下标int[] items = {getIndexForItem(1), getIndexForItem(2),getIndexForItem(3), getIndexForItem(4),getIndexForItem(5)};mItems = items;// 通过循环为每张图片设定位置for (int i = 0; i < items.length; i++) {Image3DView childView = (Image3DView) getChildAt(items[i]);childView.layout(left + IMAGE_PADDING, 0, left+ mImageWidth - IMAGE_PADDING, mHeight);childView.initImageViewBitmap();left = left + mImageWidth;}refreshImageShowing();}forceToRelayout = false;}}public interface OnFocusListener{void changeImage();void onFocus();void setValue(String value);}private OnFocusListener onFocusListener;public void setonFocusListener(OnFocusListener onFocusListener){this.onFocusListener = onFocusListener;}@Overridepublic boolean dispatchKeyEvent(KeyEvent event) {onFocusListener.changeImage();if (event.getAction() == KeyEvent.ACTION_DOWN){switch (event.getKeyCode()){//按下键 响应回调case KeyEvent.KEYCODE_DPAD_DOWN:if (onFocusListener != null){onFocusListener.onFocus();}break;//按确定键case KeyEvent.KEYCODE_DPAD_CENTER:Toast.makeText(getContext(),"点击了图片"+(currentPage%7+1),Toast.LENGTH_SHORT).show();break;//右键case KeyEvent.KEYCODE_DPAD_RIGHT:scrollToNext();if (onFocusListener !=null){onFocusListener.setValue((currentPage%7+1)+"");}break;//左键case KeyEvent.KEYCODE_DPAD_LEFT:scrollToPrevious();if (onFocusListener !=null){onFocusListener.setValue((currentPage%7+1)+"");}break;}}return true;}@Overridepublic boolean onTouchEvent(MotionEvent event) {if (mScroller.isFinished()) {if (mVelocityTracker == null) {mVelocityTracker = VelocityTracker.obtain();}mVelocityTracker.addMovement(event);int action = event.getAction();float x = event.getX();switch (action) {case MotionEvent.ACTION_DOWN:// 记录按下时的横坐标mLastMotionX = x;break;case MotionEvent.ACTION_MOVE:int disX = (int) (mLastMotionX - x);mLastMotionX = x;scrollBy(disX, 0);// 当发生移动时刷新图片的显示状态refreshImageShowing();break;case MotionEvent.ACTION_UP:mVelocityTracker.computeCurrentVelocity(1000);int velocityX = (int) mVelocityTracker.getXVelocity();if (shouldScrollToNext(velocityX)) {// 滚动到下一张图onFocusListener.changeImage();onFocusListener.setValue(String.valueOf(mCurrentImage));scrollToNext();} else if (shouldScrollToPrevious(velocityX)) {// 滚动到上一张图onFocusListener.setValue(String.valueOf(mCurrentImage));scrollToPrevious();} else {// 滚动回当前图片scrollBack();}if (mVelocityTracker != null) {mVelocityTracker.recycle();mVelocityTracker = null;}break;}}return true;}/*** 根据当前的触摸状态来决定是否屏蔽子控件的交互能力。*/@Overridepublic boolean onInterceptTouchEvent(MotionEvent ev) {int action = ev.getAction();if ((action == MotionEvent.ACTION_MOVE)&& (mTouchState != TOUCH_STATE_REST)) {return true;}float x = ev.getX();switch (action) {case MotionEvent.ACTION_DOWN:mLastMotionX = x;mTouchState = TOUCH_STATE_REST;break;case MotionEvent.ACTION_MOVE:int xDiff = (int) Math.abs(mLastMotionX - x);if (xDiff > mTouchSlop) {mTouchState = TOUCH_STATE_SCROLLING;}break;case MotionEvent.ACTION_UP:default:mTouchState = TOUCH_STATE_REST;break;}return mTouchState != TOUCH_STATE_REST;}@Overridepublic void computeScroll() {if (mScroller.computeScrollOffset()) {scrollTo(mScroller.getCurrX(), mScroller.getCurrY());refreshImageShowing();postInvalidate();}}/*** 设置图片滚动的监听器,每当有图片滚动时会回调此接口。** @param listener 图片滚动监听器*/public void setOnImageSwitchListener(OnImageSwitchListener listener) {mListener = listener;}/*** 设置当前显示图片的下标,注意如果该值小于零或大于等于图片的总数量,图片则无法正常显示。** @param currentImage 图片的下标*/public void setCurrentImage(int currentImage) {mCurrentImage = currentImage;requestLayout();}/*** 滚动到下一张图片。*/public void scrollToNext() {if (mScroller.isFinished()) {currentPage++;int disX = mImageWidth - getScrollX();checkImageSwitchBorder(SCROLL_NEXT);if (mListener != null) {mListener.onImageSwitch(mCurrentImage);}beginScroll(getScrollX(), 0, disX, 0, SCROLL_NEXT);}}/*** 滚动到上一张图片。*/public void scrollToPrevious() {if (mScroller.isFinished()) {if (currentPage ==0){currentPage = 7;}elsecurrentPage--;int disX = -mImageWidth - getScrollX();checkImageSwitchBorder(SCROLL_PREVIOUS);if (mListener != null) {mListener.onImageSwitch(mCurrentImage);}beginScroll(getScrollX(), 0, disX, 0, SCROLL_PREVIOUS);}}/*** 滚动回原图片。*/public void scrollBack() {if (mScroller.isFinished()) {beginScroll(getScrollX(), 0, -getScrollX(), 0, SCROLL_BACK);}}/*** 回收所有图片对象,释放内存。*/public void clear() {for (int i = 0; i < mCount; i++) {Image3DView childView = (Image3DView) getChildAt(i);childView.recycleBitmap();}}/*** 让控件中的所有图片开始滚动。*/private void beginScroll(int startX, int startY, int dx, int dy,final int action) {int duration = (int) (700f / mImageWidth * Math.abs(dx));mScroller.startScroll(startX, startY, dx, dy, duration);invalidate();handler.postDelayed(new Runnable() {@Overridepublic void run() {if (action == SCROLL_NEXT || action == SCROLL_PREVIOUS) {forceToRelayout = true;requestLayout();}}}, duration);}/*** 根据当前图片的下标和传入的item参数,来判断item位置上应该显示哪张图片。** @param item 取值范围是1-5* @return 对应item位置上应该显示哪张图片。*/private int getIndexForItem(int item) {int index = -1;index = mCurrentImage + item - 3;while (index < 0) {index = index + mCount;}while (index > mCount - 1) {index = index - mCount;}return index;}/*** 刷新所有图片的显示状态,包括当前的旋转角度。*/private void refreshImageShowing() {for (int i = 0; i < mItems.length; i++) {Image3DView childView = (Image3DView) getChildAt(mItems[i]);childView.setRotateData(i, getScrollX());childView.invalidate();}}/*** 检查图片的边界,防止图片的下标超出规定范围。*/private void checkImageSwitchBorder(int action) {if (action == SCROLL_NEXT && ++mCurrentImage >= mCount) {mCurrentImage = 0;} else if (action == SCROLL_PREVIOUS && --mCurrentImage < 0) {mCurrentImage = mCount - 1;}}/*** 判断是否应该滚动到下一张图片。*/private boolean shouldScrollToNext(int velocityX) {return velocityX < -SNAP_VELOCITY || getScrollX() > mImageWidth / 2;}/*** 判断是否应该滚动到上一张图片。*/private boolean shouldScrollToPrevious(int velocityX) {return velocityX > SNAP_VELOCITY || getScrollX() < -mImageWidth / 2;}/*** 图片滚动的监听器*/public interface OnImageSwitchListener {/*** 当图片滚动时会回调此方法** @param currentImage 当前图片的坐标*/void onImageSwitch(int currentImage);}
}
7.MainActivity
public class MainActivity extends Activity {private static final String TAG="MainActivity";private Button btn;private Button btn2;private Image3DSwitchView image3DSwitchView;private Image3DView image3DView1,image3DView2,image3DView3,image3DView4,image3DView5,image3DView6,image3DView7;String url = "https://api.ixiaowai.cn/gqapi/gqapi.php";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn = (Button) findViewById(R.id.btn);btn2 = (Button) findViewById(R.id.btn2);image3DSwitchView = (Image3DSwitchView) findViewById(R.id.image_switch_view);image3DView1=(Image3DView)findViewById(R.id.image1);image3DView2=(Image3DView)findViewById(R.id.image2);image3DView3=(Image3DView)findViewById(R.id.image3);image3DView4=(Image3DView)findViewById(R.id.image4);image3DView5=(Image3DView)findViewById(R.id.image5);image3DView6=(Image3DView)findViewById(R.id.image6);image3DView7=(Image3DView)findViewById(R.id.image7);btn2.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {new Thread(new Runnable() {@Overridepublic void run() {Bitmap bmp = getURLimage(url);Message msg = new Message();msg.what = 0;msg.obj = bmp;handle.sendMessage(msg);}}).start();}});btn.setOnKeyListener(new View.OnKeyListener() {@Overridepublic boolean onKey(View v, int keyCode, KeyEvent event) {if (keyCode == KeyEvent.KEYCODE_DPAD_UP && event.getAction()== KeyEvent.ACTION_DOWN)image3DSwitchView.requestFocus();return true;}});//设置监听,并实现接口image3DSwitchView.setonFocusListener(new Image3DSwitchView.OnFocusListener() {@Overridepublic void changeImage() {new Thread(new Runnable() {@Overridepublic void run() {Bitmap bmp = getURLimage(url);Message msg = new Message();msg.what = 0;msg.obj = bmp;handle.sendMessage(msg);}}).start();}@Overridepublic void onFocus() {btn.requestFocus();}@Overridepublic void setValue(String value) {btn.setText(value+"/7");}});}//在消息队列中实现对控件的更改private Handler handle = new Handler() {public void handleMessage(Message msg) {switch (msg.what) {case 0:Bitmap bmp=(Bitmap)msg.obj;int i=image3DSwitchView.getmCurrentImage();Image3DView image3DView=(Image3DView) image3DSwitchView.getChildAt(i);Log.d(TAG, "handleMessage: "+image3DView);image3DView.setImageBitmap(bmp);break;}};};//加载图片public Bitmap getURLimage(String url) {Bitmap bmp = null;try {URL myurl = new URL(url);// 获得连接HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();conn.setConnectTimeout(6000);//设置超时conn.setDoInput(true);conn.setUseCaches(false);//不缓存conn.connect();InputStream is = conn.getInputStream();//获得图片的数据流bmp = BitmapFactory.decodeStream(is);//读取图像数据is.close();} catch (Exception e) {e.printStackTrace();}return bmp;}}
8.效果展示
进行向左滑动的时候,会刷新一张图片,实现轮播图效果,点击更换图片会让当前中间的图片进行更换。
这篇关于安卓中实现动态轮播图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!