高仿優酷Android客戶端圖片左右滑動(自動切換)

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

具體思路:

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

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

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

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

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


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

            



工程結構如下圖所示:

main.xml:

[java] view plain copy
  1.   

然後是具體的佈局文件及代碼實現:

main.xml:

<?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:

[java] view plain copy
  1. package com.tony.viewpager;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.concurrent.Executors;  
  6. import java.util.concurrent.ScheduledExecutorService;  
  7. import java.util.concurrent.TimeUnit;  
  8.   
  9.   
  10. import android.app.Activity;  
  11. import android.os.Bundle;  
  12. import android.os.Handler;  
  13. import android.os.Parcelable;  
  14. import android.support.v4.view.PagerAdapter;  
  15. import android.support.v4.view.ViewPager;  
  16. import android.support.v4.view.ViewPager.OnPageChangeListener;  
  17. import android.view.View;  
  18. import android.widget.ImageView;  
  19. import android.widget.ImageView.ScaleType;  
  20. import android.widget.TextView;  
  21.   
  22. /** 
  23.  * 仿優酷Android客戶端圖片左右滑動 
  24.  *  
  25.  */  
  26. public class MyViewPagerActivity extends Activity {  
  27.     private ViewPager viewPager; // android-support-v4中的滑動組件  
  28.     private List<ImageView> imageViews; // 滑動的圖片集合  
  29.   
  30.     private String[] titles; // 圖片標題  
  31.     private int[] imageResId; // 圖片ID  
  32.     private List<View> dots; // 圖片標題正文的那些點  
  33.   
  34.     private TextView tv_title;  
  35.     private int currentItem = 0// 當前圖片的索引號  
  36.   
  37.     // An ExecutorService that can schedule commands to run after a given delay,  
  38.     // or to execute periodically.  
  39.     private ScheduledExecutorService scheduledExecutorService;  
  40.   
  41.     // 切換當前顯示的圖片  
  42.     private Handler handler = new Handler() {  
  43.         public void handleMessage(android.os.Message msg) {  
  44.             viewPager.setCurrentItem(currentItem);// 切換當前顯示的圖片  
  45.         };  
  46.     };  
  47.   
  48.     @Override  
  49.     public void onCreate(Bundle savedInstanceState) {  
  50.         super.onCreate(savedInstanceState);  
  51.         setContentView(R.layout.main);  
  52.   
  53.         imageResId = new int[] { R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e };  
  54.         titles = new String[imageResId.length];  
  55.         titles[0] = "鞏俐不低俗,我就不能低俗";  
  56.         titles[1] = "撲樹又回來啦!再唱經典老歌引萬人大合唱";  
  57.         titles[2] = "揭祕北京電影如何升級";  
  58.         titles[3] = "樂視網TV版大派送";  
  59.         titles[4] = "熱血屌絲的反殺";  
  60.   
  61.         imageViews = new ArrayList<ImageView>();  
  62.   
  63.         // 初始化圖片資源  
  64.         for (int i = 0; i < imageResId.length; i++) {  
  65.             ImageView imageView = new ImageView(this);  
  66.             imageView.setImageResource(imageResId[i]);  
  67.             imageView.setScaleType(ScaleType.CENTER_CROP);  
  68.             imageViews.add(imageView);  
  69.         }  
  70.   
  71.           
  72.         dots = new ArrayList<View>();  
  73.         dots.add(findViewById(R.id.v_dot0));  
  74.         dots.add(findViewById(R.id.v_dot1));  
  75.         dots.add(findViewById(R.id.v_dot2));  
  76.         dots.add(findViewById(R.id.v_dot3));  
  77.         dots.add(findViewById(R.id.v_dot4));  
  78.   
  79.         tv_title = (TextView) findViewById(R.id.tv_title);  
  80.         tv_title.setText(titles[0]);//  
  81.   
  82.         viewPager = (ViewPager) findViewById(R.id.vp);  
  83.         viewPager.setAdapter(new MyAdapter());// 設置填充ViewPager頁面的適配器  
  84.         // 設置一個監聽器,當ViewPager中的頁面改變時調用  
  85.         viewPager.setOnPageChangeListener(new MyPageChangeListener());  
  86.   
  87.     }  
  88.   
  89.     @Override  
  90.     protected void onStart() {  
  91.         scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();  
  92.         // 當Activity顯示出來後,每兩秒鐘切換一次圖片顯示  
  93.         scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 12, TimeUnit.SECONDS);  
  94.         super.onStart();  
  95.     }  
  96.   
  97.     @Override  
  98.     protected void onStop() {  
  99.         // 當Activity不可見的時候停止切換  
  100.         scheduledExecutorService.shutdown();  
  101.         super.onStop();  
  102.     }  
  103.   
  104.     /** 
  105.      * 換行切換任務 
  106.      *  
  107.      * @author Administrator 
  108.      *  
  109.      */  
  110.     private class ScrollTask implements Runnable {  
  111.   
  112.         public void run() {  
  113.             synchronized (viewPager) {  
  114.                 System.out.println("currentItem: " + currentItem);  
  115.                 currentItem = (currentItem + 1) % imageViews.size();  
  116.                 handler.obtainMessage().sendToTarget(); // 通過Handler切換圖片  
  117.             }  
  118.         }  
  119.   
  120.     }  
  121.   
  122.     /** 
  123.      * 當ViewPager中頁面的狀態發生改變時調用 
  124.      *  
  125.      * @author Administrator 
  126.      *  
  127.      */  
  128.     private class MyPageChangeListener implements OnPageChangeListener {  
  129.         private int oldPosition = 0;  
  130.   
  131.         /** 
  132.          * This method will be invoked when a new page becomes selected. 
  133.          * position: Position index of the new selected page. 
  134.          */  
  135.         public void onPageSelected(int position) {  
  136.             currentItem = position;  
  137.             tv_title.setText(titles[position]);  
  138.             dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);  
  139.             dots.get(position).setBackgroundResource(R.drawable.dot_focused);  
  140.             oldPosition = position;  
  141.         }  
  142.   
  143.         public void onPageScrollStateChanged(int arg0) {  
  144.   
  145.         }  
  146.   
  147.         public void onPageScrolled(int arg0, float arg1, int arg2) {  
  148.   
  149.         }  
  150.     }  
  151.   
  152.     /** 
  153.      * 填充ViewPager頁面的適配器 
  154.      *  
  155.      * @author Administrator 
  156.      *  
  157.      */  
  158.     private class MyAdapter extends PagerAdapter {  
  159.   
  160.         @Override  
  161.         public int getCount() {  
  162.             return imageResId.length;  
  163.         }  
  164.   
  165.         @Override  
  166.         public Object instantiateItem(View arg0, int arg1) {  
  167.             ((ViewPager) arg0).addView(imageViews.get(arg1));  
  168.             return imageViews.get(arg1);  
  169.         }  
  170.   
  171.         @Override  
  172.         public void destroyItem(View arg0, int arg1, Object arg2) {  
  173.             ((ViewPager) arg0).removeView((View) arg2);  
  174.         }  
  175.   
  176.         @Override  
  177.         public boolean isViewFromObject(View arg0, Object arg1) {  
  178.             return arg0 == arg1;  
  179.         }  
  180.   
  181.         @Override  
  182.         public void restoreState(Parcelable arg0, ClassLoader arg1) {  
  183.   
  184.         }  
  185.   
  186.         @Override  
  187.         public Parcelable saveState() {  
  188.             return null;  
  189.         }  
  190.   
  191.         @Override  
  192.         public void startUpdate(View arg0) {  
  193.   
  194.         }  
  195.   
  196.         @Override  
  197.         public void finishUpdate(View arg0) {  
  198.   
  199.         }  
  200.     }  
  201. }  

Drawable目錄下
btn_back_selector.xml:

[java] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.   
  4.     <item android:drawable="@drawable/btn_top_pressed" android:state_focused="true"></item>  
  5.     <item android:drawable="@drawable/btn_top_pressed" android:state_pressed="true"></item>  
  6.     <item android:drawable="@drawable/btn_top_pressed" android:state_selected="true"></item>  
  7.     <item android:drawable="@drawable/title_bk"></item>  
  8.   
  9. </selector>  


btn_top_pressed.xml:

[java] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:shape="rectangle" >  
  4.   
  5.     <gradient  
  6.         android:angle="270"  
  7.         android:endColor="#009ad6"  
  8.         android:startColor="#11264f" />  
  9.   
  10. </shape>  

dot_focused.xml:
[java] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:shape="oval" >  
  4.   
  5.     <solid android:color="#aaFFFFFF" />  
  6.   
  7.     <corners android:radius="5dip" />  
  8.   
  9. </shape>  

dot_normal.xml:
[java] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:shape="oval" >  
  4.   
  5.     <solid android:color="#33000000" />  
  6.   
  7.     <corners android:radius="5dip" />  
  8.   
  9. </shape>  

title_bk.xml:
[java] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:shape="rectangle" >  
  4.   
  5.     <gradient  
  6.         android:angle="270"  
  7.         android:endColor="#11264f"  
  8.         android:startColor="#009ad6" />  
  9.   
  10. </shape>  

源碼下載地址:

http://download.csdn.net/detail/t12x3456/4751688

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章