Gallery 实现图片定时无限循环切换

最近看到很多软件里面会有广告或内容定时自动切换的功能,然后查了下资料 自己用Gallery也做了个类似的能,现跟大家分享下。

1、自定义CustomGallery继承Gallery

package views;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Gallery;


public class CustomGallery extends Gallery {


    public CustomGallery(Context context) {
        super(context);
    }


    public CustomGallery(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    public CustomGallery(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                           float velocityY) {
        boolean left = isFlingLeft(e1, e2);
        int keyEvent;
        if (left) {
            keyEvent = KeyEvent.KEYCODE_DPAD_LEFT;
        } else {
            keyEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
        }
        onKeyDown(keyEvent, null);
// 返回false或true 即可去除滑动时的惯性
        return false;
    }


    // 设置只要手指在界面上滑动就可以切换内容,不需要滑动一半才换页
    public boolean isFlingLeft(MotionEvent e1, MotionEvent e2) {
        return e1.getX() < e2.getX();
    }
}



2、设置Gallery内容 显示用的Adapter,继承BaseAdapter。

package Adapters;
import views.CustomGallery;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import com.example.gallery.R;


public class CustomGalleryAdapter extends BaseAdapter {


    private int[] imageIds;
    private Context mContext;


    public CustomGalleryAdapter(Context context, int[] ids) {
        this.mContext = context;
        this.imageIds = ids;
    }


    @Override
    public int getCount() {
// 模拟实现无限循环,实际是有限制的,因为Max.Value是有限值的
        return Integer.MAX_VALUE;
    }


    @Override
    public Object getItem(int position) {
        return imageIds[position % imageIds.length];
    }


    @Override
    public long getItemId(int position) {
        return position % imageIds.length;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView = null;
// System.out.println("position------->" + position);
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(
                    R.layout.image_layout, null);
            imageView = (ImageView) convertView.findViewById(R.id.image);
// 将ImageView所在的布局设置为与Gallery等宽的大小
            LayoutParams params = new CustomGallery.LayoutParams(
                    CustomGallery.LayoutParams.MATCH_PARENT,
                    CustomGallery.LayoutParams.WRAP_CONTENT);
            convertView.setLayoutParams(params);
        }
        imageView = (ImageView) convertView.findViewById(R.id.image);
        Drawable draw = mContext.getResources().getDrawable(
                imageIds[position % imageIds.length]);
        imageView.setImageDrawable(draw);
        return convertView;
    }


}



3、在MainActivity中具体实现。

        package com.example.gallery;


        import java.util.Timer;
        import java.util.TimerTask;
        import views.CustomGallery;
        import Adapters.CustomGalleryAdapter;
        import android.app.Activity;
        import android.content.Context;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.AdapterView;
        import android.widget.AdapterView.OnItemClickListener;
        import android.widget.AdapterView.OnItemSelectedListener;
        import android.widget.ImageView;
        import android.widget.Toast;


public class MainActivity extends Activity {
    private CustomGallery mGallery;
    private Context mContext;
    private int[] ids;
    private ImageView[] imageViewIds;
    private static final int PERIOD = 3000;//周期3秒
    private static final int DELAY = 3000;//延时3秒


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.mContext = this;
        imageViewIds = new ImageView[]{(ImageView) findViewById(R.id.dot1),
                (ImageView) findViewById(R.id.dot2),
                (ImageView) findViewById(R.id.dot3),
                (ImageView) findViewById(R.id.dot4)};
        mGallery = (CustomGallery) findViewById(R.id.gallery);
        ids = new int[]{R.drawable.a1, R.drawable.a2, R.drawable.a3,
                R.drawable.a4};
        CustomGalleryAdapter adapter = new CustomGalleryAdapter(this, ids);
        mGallery.setAdapter(adapter);
// 实现左右循环的关键点,将Gallery开始选中显示的位置设置在中间点,否则无法实现左边循环切换,因为默认开始位置为0
        mGallery.setSelection((Integer.MAX_VALUE - 6) / 2);
//设置选中监听事件
        mGallery.setOnItemSelectedListener(onItemSelectesListener);
//设置点击监听事件
        mGallery.setOnItemClickListener(onItemClickListener);
// 用定时器实现定时自动播放图片或其他内容
        Timer timer = new Timer();
        timer.schedule(new GalleryTimerTask(), DELAY, PERIOD);
    }


    private OnItemSelectedListener onItemSelectesListener = new OnItemSelectedListener() {


        @Override
        public void onItemSelected(AdapterView parent, View view,
                                   int position, long id) {
            int index = (int) parent.getItemIdAtPosition(position);
// 将选中的图片对应的小圆点设置成深色背景
            imageViewIds[index].setImageDrawable(MainActivity.this
                    .getResources().getDrawable(
                            R.drawable.base_indicator_dot_selected));
// 将选中位置的后一张的小圆点背景还原
            imageViewIds[(position + 1) % imageViewIds.length]
                    .setImageDrawable(MainActivity.this.getResources()
                            .getDrawable(R.drawable.base_indicator_dot_normal));
// 当选中的位置不是0位置时,将对应的小圆点的背景还原
            if (position != 0) {
                imageViewIds[(position - 1) % imageViewIds.length]
                        .setImageDrawable(MainActivity.this.getResources()
                                .getDrawable(
                                        R.drawable.base_indicator_dot_normal));
            }
        }


        @Override
        public void onNothingSelected(AdapterView parent) {


        }
    };


    private OnItemClickListener onItemClickListener = new OnItemClickListener() {


        @Override
        public void onItemClick(AdapterView parent, View view, int position,
                                long id) {
            int index = (int) mGallery.getItemIdAtPosition(position);
            switch (index) {
                case 0:
                    Toast.makeText(mContext, "这是第" + index + "项!", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    Toast.makeText(mContext, "这是第" + index + "项!", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    Toast.makeText(mContext, "这是第" + index + "项!", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    Toast.makeText(mContext, "这是第" + index + "项!", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };


    class GalleryTimerTask extends TimerTask {


        @Override
        public void run() {
// 更新界面必须在主线程中,记住哦!
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
// 实现自动选中图片,即自动播放下一张
                    int index = mGallery.getSelectedItemPosition();
                    mGallery.setSelection(index + 1);
                }
            });
        }
    }


}

4、对应的XMl文件,如下

1)主布局文件




    


        


        


            


            


            


            
        
    




2)Gallery中显示内容的布局



    


 







 

你可能感兴趣的:(android)