Android實現滑動圖片(ViewPager)

最近在學習android,看了幾天教材之後,決定親手做一些demo,在實踐中不斷成長

下面是從一個大神的博客中摘取的使用ViewPager實現滾動圖片的demo,我在學習這個demo的時候遇到很多問題,現在把對這個demo的學習過程記錄下來(不斷補充中),由於本人爲初學者,所以寫的內容可能比較初級,希望對同樣的初學者可以提供一定的幫助。

自學內容:

1、Android實現滑動圖片(ViewPager)學習之一:佈局

2、Android實現滑動圖片(ViewPager)學習之二: Android中Handler的初步認識(一)

3、Android實現滑動圖片(ViewPager)學習之三: Android中Handler的初步認識(二)

4、Android實現滑動圖片(ViewPager)學習之四: Android中Handler的初步認識(三)

5、Android實現滑動圖片(ViewPager)學習之五: Android中Handler的初步認識(四)


----------------------------------------------------------------------------------------------------分割線----------------------------------------------------------------------------


以下是ViewPager實現滾動圖片的原文:


原文鏈接:http://blog.csdn.net/t12x3456/article/details/8160128


本例是用ViewPager去做的實現,支持自動滑動和手動滑動,不僅優酷網,實際上有很多商城和門戶網站都有類似的實現:

具體思路:

1. 工程中需要添加android-support-v4.jar,才能使用ViewPager控件.

2. 圖片的自動切換: 可使用Timer或者ScheduledExecutorService,這個有多重方式可以實現.

    同時要切換底部的dots(園點)

3.Handler+Message機制更新UI,這個相信大家都很熟練,不再描述

4. 實現的一些細節:注意本例中的優化:圖片的自動切換啓動了其他的線程,要在Activity在可見到不可見的狀態,也就是在onStop()方法中將線程停止,在onStart()方法中開啓線程。否則,Timer沒有停止,或者反覆開啓,會引起較大的內存消耗,時間一長就程序就會崩掉。 還有,就是在跳轉到其他Activity的過程中會出現畫面的卡頓


下面看一下效果圖和具體代碼:

            



工程結構如下圖所示:

main.xml:


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:angle="270"
        android:endColor="#11264f"
        android:startColor="#009ad6" />

</shape>


<P>
</P><P><STRONG>然後是具體的佈局文件及代碼實現:</STRONG></P><P>main.xml:</P>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="40dip"
        android:background="@drawable/title_bk" >

        <ImageButton
            android:id="@+id/btn_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/btn_back_selector"
            android:src="@drawable/btn_back" />

        <View
            android:id="@+id/line0"
            android:layout_width="1px"
            android:layout_height="fill_parent"
            android:layout_toRightOf="@id/btn_back"
            android:background="#aa11264f" />

        <View
            android:layout_width="1px"
            android:layout_height="fill_parent"
            android:layout_toRightOf="@id/line0"
            android:background="#009ad6" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="優酷客戶端"
            android:textColor="#FFFFFF"
            android:textSize="20sp" />
    </RelativeLayout>

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="140dip" >

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

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

            <TextView
                android:id="@+id/tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="中國家庭院校園區域名字體現"
                android:textColor="#ffffff" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="3dip"
                android:gravity="center" >

                <View
                    android:id="@+id/v_dot0"
                    style="@style/dot_style"
                    android:background="@drawable/dot_focused" />

                <View
                    android:id="@+id/v_dot1"
                    style="@style/dot_style" />

                <View
                    android:id="@+id/v_dot2"
                    style="@style/dot_style" />

                <View
                    android:id="@+id/v_dot3"
                    style="@style/dot_style" />

                <View
                    android:id="@+id/v_dot4"
                    style="@style/dot_style" />
            </LinearLayout>
        </LinearLayout>
    </FrameLayout>

</LinearLayout>

MyViewPagerActivity:

package com.tony.viewpager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

/**
 * 仿優酷Android客戶端圖片左右滑動
 * 
 */
public class MyViewPagerActivity extends Activity {
	private ViewPager viewPager; // android-support-v4中的滑動組件
	private List<ImageView> imageViews; // 滑動的圖片集合

	private String[] titles; // 圖片標題
	private int[] imageResId; // 圖片ID
	private List<View> dots; // 圖片標題正文的那些點

	private TextView tv_title;
	private int currentItem = 0; // 當前圖片的索引號

	// An ExecutorService that can schedule commands to run after a given delay,
	// or to execute periodically.
	private ScheduledExecutorService scheduledExecutorService;

	// 切換當前顯示的圖片
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			viewPager.setCurrentItem(currentItem);// 切換當前顯示的圖片
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		imageResId = new int[] { R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e };
		titles = new String[imageResId.length];
		titles[0] = "鞏俐不低俗,我就不能低俗";
		titles[1] = "撲樹又回來啦!再唱經典老歌引萬人大合唱";
		titles[2] = "揭祕北京電影如何升級";
		titles[3] = "樂視網TV版大派送";
		titles[4] = "熱血屌絲的反殺";

		imageViews = new ArrayList<ImageView>();

		// 初始化圖片資源
		for (int i = 0; i < imageResId.length; i++) {
			ImageView imageView = new ImageView(this);
			imageView.setImageResource(imageResId[i]);
			imageView.setScaleType(ScaleType.CENTER_CROP);
			imageViews.add(imageView);
		}

		
		dots = new ArrayList<View>();
		dots.add(findViewById(R.id.v_dot0));
		dots.add(findViewById(R.id.v_dot1));
		dots.add(findViewById(R.id.v_dot2));
		dots.add(findViewById(R.id.v_dot3));
		dots.add(findViewById(R.id.v_dot4));

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

		viewPager = (ViewPager) findViewById(R.id.vp);
		viewPager.setAdapter(new MyAdapter());// 設置填充ViewPager頁面的適配器
		// 設置一個監聽器,當ViewPager中的頁面改變時調用
		viewPager.setOnPageChangeListener(new MyPageChangeListener());

	}

	@Override
	protected void onStart() {
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		// 當Activity顯示出來後,每兩秒鐘切換一次圖片顯示
		scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 2, TimeUnit.SECONDS);
		super.onStart();
	}

	@Override
	protected void onStop() {
		// 當Activity不可見的時候停止切換
		scheduledExecutorService.shutdown();
		super.onStop();
	}

	/**
	 * 換行切換任務
	 * 
	 * @author Administrator
	 * 
	 */
	private class ScrollTask implements Runnable {

		public void run() {
			synchronized (viewPager) {
				System.out.println("currentItem: " + currentItem);
				currentItem = (currentItem + 1) % imageViews.size();
				handler.obtainMessage().sendToTarget(); // 通過Handler切換圖片
			}
		}

	}

	/**
	 * 當ViewPager中頁面的狀態發生改變時調用
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyPageChangeListener implements OnPageChangeListener {
		private int oldPosition = 0;

		/**
		 * This method will be invoked when a new page becomes selected.
		 * position: Position index of the new selected page.
		 */
		public void onPageSelected(int position) {
			currentItem = position;
			tv_title.setText(titles[position]);
			dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
			dots.get(position).setBackgroundResource(R.drawable.dot_focused);
			oldPosition = position;
		}

		public void onPageScrollStateChanged(int arg0) {

		}

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

		}
	}

	/**
	 * 填充ViewPager頁面的適配器
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return imageResId.length;
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(imageViews.get(arg1));
			return imageViews.get(arg1);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

		@Override
		public void finishUpdate(View arg0) {

		}
	}
}

Drawable目錄下
btn_back_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/btn_top_pressed" android:state_focused="true"></item>
    <item android:drawable="@drawable/btn_top_pressed" android:state_pressed="true"></item>
    <item android:drawable="@drawable/btn_top_pressed" android:state_selected="true"></item>
    <item android:drawable="@drawable/title_bk"></item>

</selector>

btn_top_pressed.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:angle="270"
        android:endColor="#009ad6"
        android:startColor="#11264f" />

</shape>

dot_focused.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >

    <solid android:color="#aaFFFFFF" />

    <corners android:radius="5dip" />

</shape>

dot_normal.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >

    <solid android:color="#33000000" />

    <corners android:radius="5dip" />

</shape>

title_bk.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:angle="270"
        android:endColor="#11264f"
        android:startColor="#009ad6" />

</shape>


源碼下載地址:

http://download.csdn.net/detail/t12x3456/4751688
發佈了31 篇原創文章 · 獲贊 34 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章