Android图片轮播的使用教程(本地图片轮播)
图片轮播一般设置在APP首页,添加这个可以进行广告的轮播,类似于京东、淘宝首页的广告自由切换的效果。
1、主要原理就是利用定时任务器定时切换ViewPager的页面。
2、里面用了一个读取网络图片的插件,做客户端使用本地图片轮播的情况比较少(虽然本地图片轮播这种情况较少但是我还是要讲一下)
先上一个效果图:
1.首页布局文件activity_home.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ededed"
tools:context="com.stx.fleshfruit.HomeActivity" >
<!-- 图片轮播 -->
<com.stx.fleshfruit.scroll.ScrollImage
android:id="@+id/myscrollimg"
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_below="@+id/top" />
<!-- 顶部 -->
<RelativeLayout
android:id="@+id/top"
android:layout_width="match_parent"
android:layout_height="70dp"
android:background="@drawable/mmtitle_bg"
android:clipToPadding="true"
android:fitsSystemWindows="true" >
<Button
android:id="@+id/serach"
android:layout_width="23dp"
android:layout_height="23dp"
android:layout_alignBottom="@+id/textView1"
android:layout_toLeftOf="@+id/qr_code"
android:background="@drawable/serach" />
<Button
android:id="@+id/qr_code"
android:layout_width="28dp"
android:layout_height="28dp"
android:layout_alignBottom="@+id/serach"
android:layout_alignParentRight="true"
android:background="@drawable/qr_code" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="22dp"
android:layout_marginTop="10dp"
android:text="首页"
android:textColor="#ffffff"
android:textSize="20sp" />
</RelativeLayout>
<!-- 中间导航栏 -->
<!-- 每日推荐 -->
<!-- 底部菜单栏 -->
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="10dp"
android:layout_height="30dp"
android:layout_alignBottom="@+id/linearLayout2"
android:layout_alignParentLeft="true"
android:layout_marginTop="10dp"
android:background="#FF6347"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:id="@+id/gongneng"
android:layout_width="match_parent"
android:layout_height="85dp"
android:layout_alignParentLeft="true"
android:layout_below="@+id/myscrollimg"
android:layout_marginTop="16dp"
android:background="@drawable/mmtitle_bg1" >
<LinearLayout
android:id="@+id/gongneng_taocan"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:clickable="true"
android:orientation="vertical"
android:paddingTop="6dp" >
<ImageView
android:id="@+id/taocan"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_centerVertical="true"
android:layout_gravity="center_horizontal"
android:background="@drawable/taocan"
android:onClick="taocan" />
<TextView
android:id="@+id/taocan_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="套餐"
android:textColor="#595959"
android:textSize="15dp" />
</LinearLayout>
<LinearLayout
android:id="@+id/gongneng_pinpan"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:clickable="true"
android:orientation="vertical"
android:paddingTop="6dp" >
<ImageView
android:id="@+id/pinpan"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_centerVertical="true"
android:layout_gravity="center_horizontal"
android:background="@drawable/taocan" />
<TextView
android:id="@+id/pinpan_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="拼盘"
android:textColor="#595959"
android:textSize="15dp" />
</LinearLayout>
<LinearLayout
android:id="@+id/gongneng_dandian"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:clickable="true"
android:orientation="vertical"
android:paddingTop="6dp" >
<ImageView
android:id="@+id/dandian"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_centerVertical="true"
android:layout_gravity="center_horizontal"
android:background="@drawable/taocan"
android:onClick="single" />
<TextView
android:id="@+id/textView4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="单点"
android:textColor="#595959"
android:textSize="15dp" />
</LinearLayout>
<LinearLayout
android:id="@+id/gongneng_more"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:clickable="true"
android:orientation="vertical"
android:paddingTop="6dp" >
<ImageView
android:id="@+id/more"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_centerVertical="true"
android:layout_gravity="center_horizontal"
android:background="@drawable/more" />
<TextView
android:id="@+id/more_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="礼品"
android:textColor="#595959"
android:textSize="15dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:layout_below="@+id/gongneng"
android:layout_toRightOf="@+id/linearLayout3"
android:background="#ffffff"
android:orientation="horizontal" >
<TextView
android:id="@+id/meiri"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="3dp"
android:text="每日推荐"
android:textColor="#595959"
android:textSize="15dp" />
</LinearLayout>
</RelativeLayout>
package com.example.demo2;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import com.example.demo2.ui.ScrollImage;
public class MainActivity extends Activity {
private ScrollImage scrollImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrollImage=(ScrollImage) findViewById(R.id.myscrollimg);
List<Bitmap> list = new ArrayList<Bitmap>();
//添加轮播图片
list.add(BitmapFactory.decodeResource(getResources(), R.drawable.aa));
list.add(BitmapFactory.decodeResource(getResources(), R.drawable.bb));
list.add(BitmapFactory.decodeResource(getResources(), R.drawable.fff));
int width = getWindowManager().getDefaultDisplay().getWidth();
int x=(int) (0.6*width*list.get(0).getHeight()/list.get(0).getWidth());
Log.i("MainActivity",x+"");
scrollImage.setHeight((int)(x));//图片的高度
scrollImage.setBitmapList(list);
scrollImage.start(3000);
}
}
3.自定义view
SrollView.activity
package com.example.demo2.ui;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import com.example.demo2.R;
public class ScrollImage extends RelativeLayout {
private ImageScrollView imageScrollView = null;
private PageControlView pageControlView = null;
public ScrollImage(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.scroll_image, ScrollImage.this);
imageScrollView = (ImageScrollView) this.findViewById(R.id.myImageScrollView);
pageControlView = (PageControlView) this.findViewById(R.id.myPageControlView);
}
/**
* 设置显示图片
* @param list 图片集合
*/
public void setBitmapList(List<Bitmap> list){
int num = list.size();
imageScrollView.removeAllViews();
for(int i = 0; i < num; i++){
ImageView imageView = new ImageView(getContext());
imageView.setImageBitmap(list.get(i));
imageView.setScaleType(ScaleType.FIT_XY);
imageScrollView.addView(imageView);
}
/** 设置圆圈的数量 **/
pageControlView.setCount(imageScrollView.getChildCount());
/** 初始化圆圈 **/
pageControlView.generatePageControl(0);
/** 设置视图切换回调函数实现 **/
imageScrollView.setScrollToScreenCallback(pageControlView);
}
/**
* 设置组件的高
* @param height 高
*/
public void setHeight(int height){
android.view.ViewGroup.LayoutParams la = getLayoutParams();
la.height = height;
android.view.ViewGroup.LayoutParams lap = imageScrollView.getLayoutParams();
lap.height = height;
}
/**
* 设置组件的宽
* @param height 宽
*/
public void setWidth(int width){
android.view.ViewGroup.LayoutParams la = getLayoutParams();
la.width = width;
android.view.ViewGroup.LayoutParams lap = imageScrollView.getLayoutParams();
lap.width = width;
}
/**
* 图片开始滚动
* @param time 滚动频率,单位:毫秒
*/
public void start(int time){
imageScrollView.start(time);
}
/**
* 图片停止滚动
*/
public void stop(){
imageScrollView.stop();
}
public int getPosition(){
return imageScrollView.getCurrentScreenIndex();
}
/**
* 设置监听方法
* @param clickListener
*/
public void setClickListener(OnClickListener clickListener) {
imageScrollView.setClickListener(clickListener);
}
}
4.自定义动画圆圈数量
PageControlView.activity
package com.example.demo2.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.example.demo2.R;
import com.example.demo2.ui.ImageScrollView.ScrollToScreenCallback;
public class PageControlView extends LinearLayout implements ScrollToScreenCallback{
/** Context对象 **/
private Context context;
/** 圆圈的数量 **/
private int count;
public PageControlView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context=context;
}
/**
* 回调函数
*/
@Override
public void callback(int currentIndex) {
generatePageControl(currentIndex);
}
/** 设置选中圆圈 **/
public void generatePageControl(int currentIndex) {
this.removeAllViews();
for (int i = 0; i < this.count; i++) {
ImageView iv = new ImageView(context);
if (currentIndex == i) {
iv.setImageResource(R.drawable.page_indicator_focused);
} else {
iv.setImageResource(R.drawable.page_indicator);
}
iv.setLayoutParams(new LayoutParams(1, 0));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = 8;
layoutParams.rightMargin = 8;
iv.setLayoutParams(layoutParams);
this.addView(iv);
}
}
/** 设置圆圈数量 **/
public void setCount(int count) {
this.count = count;
}
}
5.左右滑动图片视图ImageScrollView
package com.example.demo2.ui;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;
public class ImageScrollView extends ViewGroup {
/** 滚动对象Scroller **/
private Scroller scroller = null;
/** 手势识别对象GestureDetector **/
private GestureDetector gestureDetector = null;
/** 当前屏幕索引 **/
private int currentScreenIndex = 0;
/** 设置一个标志位,防止底层的onTouch事件重复处理UP事件 **/
private boolean fling = false;
Handler handler;
int time;
OnClickListener clickListener;
public ImageScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
/** 设置布局,将子视图顺序横屏排列 **/
for ( int i = 0; i < getChildCount(); i++ ){
View child = getChildAt(i);
child.setVisibility(View.VISIBLE);
child.measure(right - left, bottom - top);
child.layout(i * getWidth(), 0, (i + 1) * getWidth(), getHeight());
}
}
/** 初始化 **/
private void initView(final Context context) {
this.scroller = new Scroller(context);
handler = new Handler();
this.gestureDetector = new GestureDetector(new OnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
if(clickListener!=null){
clickListener.onClick(ImageScrollView.this);
}
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// 防止移动过最后一页
if((distanceX > 0 && getScrollX() < getWidth() * (getChildCount() - 1))
|| (distanceX < 0 && getScrollX() > 0)){// 防止向第一页之前移动
scrollBy((int) distanceX, 0);
}
return true;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// 判断是否达到最小轻松速度,取绝对值的
if(Math.abs(velocityX) > ViewConfiguration.get(context)
.getScaledMinimumFlingVelocity()){
if(velocityX > 0 && currentScreenIndex >= 0){
fling = true;
scrollToScreen((currentScreenIndex - 1 + getChildCount()) % getChildCount());
} else if(velocityX < 0 && currentScreenIndex <= getChildCount() - 1){
fling = true;
scrollToScreen((currentScreenIndex + 1 + getChildCount()) % getChildCount());
}
}
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
});
}
/** 切换到指定屏 **/
public void scrollToScreen(int whichScreen) {
if(whichScreen != currentScreenIndex && getFocusedChild() != null
&& getFocusedChild() == getChildAt(currentScreenIndex)){
getFocusedChild().clearFocus(); // 清除焦点
}
final int delta = whichScreen * getWidth() - getScrollX();
int show = 0;
if(Math.abs(delta) < getWidth()*(getChildCount()-1) - getWidth()/2)
show = Math.abs(delta) * 2;
scroller.startScroll(getScrollX(), 0, delta, 0, show);
invalidate();
currentScreenIndex = whichScreen; // 设置当前屏幕索引
if(scrollToScreenCallback != null){ // 刷新圆圈
scrollToScreenCallback.callback(currentScreenIndex);
}
}
@Override
public void computeScroll() {
// 当滚动没有完成
if(scroller.computeScrollOffset()){
scrollTo(scroller.getCurrX(), 0);
postInvalidate();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
if(event.getAction() == MotionEvent.ACTION_UP){
handler.removeCallbacks(next);
if(time>=500)
handler.postDelayed(next, time);
if(!fling){
// 当用户停止拖动
snapToDestination();
}
fling = false;
}
return true;
}
/** 根据当前x坐标位置确定切换到第几屏 **/
private void snapToDestination() {
scrollToScreen((getScrollX() + (getWidth() / 2)) / getWidth());
}
/** 底部圆圈显示回调接口 **/
interface ScrollToScreenCallback {
public void callback(int currentIndex);
}
/** ScrollToScreenCallback回调对象 **/
private ScrollToScreenCallback scrollToScreenCallback;
/** 设置回调函数对象 **/
public void setScrollToScreenCallback(ScrollToScreenCallback scrollToScreenCallback) {
this.scrollToScreenCallback = scrollToScreenCallback;
}
public void start(int time){
if(time>500)
this.time = time;
else
this.time = 500;
handler.postDelayed(next, time);
}
public void stop(){
handler.removeCallbacks(next);
}
Runnable next = new Runnable() {
@Override
public void run() {
scrollToScreen((currentScreenIndex+1)%getChildCount());
handler.postDelayed(next, time);
}
};
public int getCurrentScreenIndex() {
return currentScreenIndex;
}
public void setClickListener(OnClickListener clickListener) {
this.clickListener = clickListener;
}
}