第三,实现自动滚动
由于我们还要手动滚动,所以自动滚动用单独一个进程来实现
- private void startAutoScroll() {
- new Thread() {
- @Override
- public void run() {
- int count = 0;
- while (mAutoScroll) {
- count = 0;
- while (count < 30) {
- count++;
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- if (mOnTouch) {// 用戶手动滑动时,停止自动滚动
- count = 0;
- }
- }
- mPosition++;
- Message msg = mHandler.obtainMessage(SCROLL, mPosition, 0);
- mHandler.sendMessage(msg);
- }
- }
- }.start();
- }
- private Handler mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case SCROLL:
- mGallery.setSelection(msg.arg1);
- break;
- }
- }
- };
第四 实现手动滚动
手动滚动时,要停止自动滚动,监听gallery的onTouch事件,DOWN时mOnTouch置为true,UP时mOnTouch置为false即可
- mGallery.setOnTouchListener(new OnTouchListener() {
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- int action = event.getAction();
- if (action == MotionEvent.ACTION_DOWN) {
- mOnTouch = true;
- } else if (action == MotionEvent.ACTION_UP) {
- mOnTouch = false;
- }
- return false;
- }
- });
到现在我们已经可以自动滚动,手动滚动时自动滚动也会停止。
我们也许还需要加上dot提示图片滚动的位置
- LinearLayout layout = (LinearLayout) findViewById(R.id.dot);
- if (mDots == null) {
- mDots = new ImageView[ids.length];
- for (int i = 0; i < ids.length; i++) {
- if (mDots[i] == null)
- mDots[i] = new ImageView(this);
- mDots[i].setBackgroundResource(R.drawable.banner_tab_unselected);
- layout.addView(mDots[i], new LinearLayout.LayoutParams(mWidth
- / ids.length + 1, LayoutParams.WRAP_CONTENT));
- }
- mDots[0].setBackgroundResource(R.drawable.banner_tab_selected);
- }
- mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> arg0, View view,
- int position, long arg3) {
- mDotPosition = position % ids.length;
- mDots[mDotPosition]
- .setBackgroundResource(R.drawable.banner_tab_selected);
- if (mDotPosition != mPreDotPosition)
- mDots[mPreDotPosition]
- .setBackgroundResource(R.drawable.banner_tab_unselected);
- mPreDotPosition = mDotPosition;
- }
- @Override
- public void onNothingSelected(AdapterView<?> arg0) {
- }
- });
转载于:https://blog.51cto.com/devinzhao/888669