android TV开发:使用ViewPager实现图片自动轮播效果

1.实现效果:ViewPager的子view响应点击事件 + 焦点脱离父控件(遥控器按键从子view直接跳到旁边控件)

(由于gif最大只能是2M,就只能录屏时间这么短,建议csdn可以上传容量更大的图片)



2.实现思路:ViewPager+自定义PagerAdapter+定时器ScheduledExecutorService

 主要关注点:

①ScheduledExecutorService(定时周期的执行任务)

public class MainActivity extends AppCompatActivity {
  private ScheduledExecutorService scheduledExecutorService;
  private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mViewPaper.setCurrentItem(currentItem);
        }
    };
	
	
//...
    @Override
    protected void onStart() {
        super.onStart();
        // 产生一个ExecutorService对象,这个对象只有一个线程可用来执行任务,若任务多于一个,任务将按先后顺序执行。
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(new ViewPageTask(), 4,4, TimeUnit.SECONDS);
    }
     private class ViewPageTask implements Runnable {
        @Override
        public void run() {
            currentItem = (currentItem + 1) % imageIds.length;
            mHandler.sendEmptyMessage(0);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
            scheduledExecutorService = null;
        }
    }
//....
}
②ViewPagerAdapter中的instantiateItem()函数
 //做了两件事,第一:将当前视图添加到container中,第二:返回当前View
        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            container.addView(images.get(position));
            ImageView imageView = images.get(position);
            imageView.setBackgroundResource(R.drawable.button_style);

            imageView.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() == KeyEvent.ACTION_DOWN) {
                        rightImgView2.requestFocusFromTouch();
                        rightImgView2.requestFocus();
                        return true;
                    }
                    if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() == KeyEvent.ACTION_DOWN) {
                        rightImgView.requestFocusFromTouch();
                        rightImgView.requestFocus();
                        return true;
                    }
                    return false;
                }
            });
            imageView.setFocusable(true);
            imageView.setFocusableInTouchMode(true);
            imageView.setClickable(true);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mContext, "点击了第" + "" + position + "张图片", Toast.LENGTH_LONG).show();
                }
            });
            return imageView;
        }
imageView是viewPager的子view,rightImgView2是viewPager旁边的控件


3.具体实现代码如下

public class MainActivity extends AppCompatActivity {
    private ViewPager mViewPaper;
    private List<ImageView> images;
    private List<View> dots;
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mViewPaper.setCurrentItem(currentItem);
        }
    };
    private int currentItem;
    //记录上一次点的位置
    private int oldPosition = 0;
    private TextView title;
    private ViewPagerAdapter adapter;
    private ScheduledExecutorService scheduledExecutorService;
    //存放图片的id
    private int[] imageIds = new int[]{
            R.drawable.a,
            R.drawable.b,
            R.drawable.c,
            R.drawable.d,
            R.drawable.e
    };
    //存放图片的标题
    private String[] titles = new String[]{
            "挑战者联盟,薛之谦又来辣",
            "老九门,又是李易峰这个傻叉",
            "红色通道,再看刘烨英俊潇洒",
            "神犬小七,小七居然是只猪",
            "灭罪师,鬼知道这是什么剧"
    };
    private ImageView rightImgView;
    private ImageView rightImgView1;
    private ImageView rightImgView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //定义mViewPaper旁边的控件
        rightImgView = new ImageView(this);
        rightImgView = (ImageView) findViewById(R.id.rightImgView);
        rightImgView.setImageResource(R.drawable.right);
        rightImgView1 = new ImageView(this);
        rightImgView1 = (ImageView) findViewById(R.id.rightImgView1);
        rightImgView1.setImageResource(R.drawable.right);
        rightImgView2 = new ImageView(this);
        rightImgView2 = (ImageView) findViewById(R.id.rightImgView3);
        rightImgView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,MyGallaryActivity.class);
                startActivity(intent);
            }
        });

        mViewPaper = (ViewPager) findViewById(R.id.vp);
        //显示的图片
        images = new ArrayList<ImageView>();
        for (int i = 0; i < imageIds.length; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(imageIds[i]);
            images.add(imageView);
        }
        //显示的小点
        dots = new ArrayList<View>();
        dots.add(findViewById(R.id.dot_0));
        dots.add(findViewById(R.id.dot_1));
        dots.add(findViewById(R.id.dot_2));
        dots.add(findViewById(R.id.dot_3));
        dots.add(findViewById(R.id.dot_4));

        title = (TextView) findViewById(R.id.title);
        title.setText(titles[0]);

        mViewPaper.setAdapter(adapter = new ViewPagerAdapter(this, images));


        //禁止手指控制滑动
        mViewPaper.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        mViewPaper.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                title.setText(titles[position]);
                dots.get(position).setBackgroundResource(R.drawable.dot_focused);
                dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);

                oldPosition = position;
                currentItem = position;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 产生一个ExecutorService对象,这个对象只有一个线程可用来执行任务,若任务多于一个,任务将按先后顺序执行。
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(new ViewPageTask(), 4,4, TimeUnit.SECONDS);
    }

    private class ViewPageTask implements Runnable {
        @Override
        public void run() {
            currentItem = (currentItem + 1) % imageIds.length;
            mHandler.sendEmptyMessage(0);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
            scheduledExecutorService = null;
        }
    }


    public class ViewPagerAdapter extends PagerAdapter {
        private List<ImageView> images;
        private Context mContext;

        public ViewPagerAdapter(Context context, List<ImageView> img) {
            this.mContext = context;
            this.images = img;
        }

        //返回要滑动的VIew的个数
        @Override
        public int getCount() {
            return images.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        //从当前container中删除指定位置(position)的View;
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(images.get(position));
        }

        //做了两件事,第一:将当前视图添加到container中,第二:返回当前View
        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            container.addView(images.get(position));
            ImageView imageView = images.get(position);
            imageView.setBackgroundResource(R.drawable.button_style);

            imageView.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() == KeyEvent.ACTION_DOWN) {
                        rightImgView2.requestFocusFromTouch();
                        rightImgView2.requestFocus();
                        return true;
                    }
                    if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() == KeyEvent.ACTION_DOWN) {
                        rightImgView.requestFocusFromTouch();
                        rightImgView.requestFocus();
                        return true;
                    }
                    return false;
                }
            });
            imageView.setFocusable(true);
            imageView.setFocusableInTouchMode(true);
            imageView.setClickable(true);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mContext, "点击了第" + "" + position + "张图片", Toast.LENGTH_LONG).show();
                }
            });
            return imageView;
        }
    }

}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000">

    <FrameLayout
        android:id="@+id/leftView"
        android:layout_marginTop="80dp"
        android:layout_marginLeft="80dp"
        android:layout_width="600dp"
        android:layout_height="300dp" >

        <android.support.v4.view.ViewPager
            android:id="@+id/vp"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="35dip"
            android:layout_gravity="bottom"
            android:background="#00000000"
            android:gravity="center"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="图片标题"
                android:textColor="@android:color/white" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="3dip"
                android:orientation="horizontal" >

                <View
                    android:id="@+id/dot_0"
                    android:layout_width="5dip"
                    android:layout_height="5dip"
                    android:layout_marginLeft="2dip"
                    android:layout_marginRight="2dip"
                    android:background="@drawable/dot_focused"/>

                <View
                    android:id="@+id/dot_1"
                    android:layout_width="5dip"
                    android:layout_height="5dip"
                    android:layout_marginLeft="2dip"
                    android:layout_marginRight="2dip"
                    android:background="@drawable/dot_normal"/>
                <View
                    android:id="@+id/dot_2"
                    android:layout_width="5dip"
                    android:layout_height="5dip"
                    android:layout_marginLeft="2dip"
                    android:layout_marginRight="2dip"
                    android:background="@drawable/dot_normal"/>
                <View
                    android:id="@+id/dot_3"
                    android:layout_width="5dip"
                    android:layout_height="5dip"
                    android:layout_marginLeft="2dip"
                    android:layout_marginRight="2dip"
                    android:background="@drawable/dot_normal"/>
                <View
                    android:id="@+id/dot_4"
                    android:layout_width="5dip"
                    android:layout_height="5dip"
                    android:layout_marginLeft="2dip"
                    android:layout_marginRight="2dip"
                    android:background="@drawable/dot_normal"/>

            </LinearLayout>
        </LinearLayout>
    </FrameLayout>

    <ImageView
        android:layout_toRightOf="@+id/leftView"
        android:layout_marginTop="80dp"
        android:layout_marginLeft="10dp"
        android:id="@+id/rightImgView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_style"
        android:src="@drawable/right"
        android:clickable="true"
        android:focusable="true"
        android:focusableInTouchMode="true" />

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/leftView"
        android:layout_marginLeft="80dp"
        android:layout_marginTop="5dp">


        <ImageView
            android:id="@+id/rightImgView"
            android:layout_width="344dp"
            android:layout_height="216dp"
            android:background="@drawable/button_style"
            android:clickable="true"
            android:focusable="true"
            android:focusableInTouchMode="true" />
        <ImageView
            android:id="@+id/rightImgView1"
            android:layout_marginLeft="370dp"
            android:layout_width="344dp"
            android:layout_height="216dp"
            android:background="@drawable/button_style"
            android:clickable="true"
            android:focusable="true"
            android:focusableInTouchMode="true" />
    </FrameLayout>
</RelativeLayout>

4.源码+apk下载

主要参考 http://blog.csdn.net/l1028386804/article/details/48049913

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值