码迷,mamicode.com
首页 > 其他好文 > 详细

ViewPager

时间:2015-02-14 13:50:36      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:viewpager


ViewPager图片自动(手动)滑动


技术分享


技术分享


技术分享



主布局文件:

    activity_main.xml

<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="1dp"
            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="140dp" >

        <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="35dp"
            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="3dp"
                android:gravity="center" >

                <!-- 此处可以去掉,只是为了演示style的使用
                     
                     style="@style/dot_style" -被引用
	                     <item name="android:layout_width">5dp</item>
			     <item name="android:layout_height">5dp</item>
			     <item name="android:background">@drawable/dot_normal</item>
			     <item name="android:layout_marginLeft">1.5dp</item>
			     <item name="android:layout_marginRight">1.5dp</item>
	                
	              <View 
                        android:id="@+id/v_dot0" 
                        style="@style/dot_style"/>-引用
	                
	                 
	              相 当于   
	              <View 
                        android:id="@+id/v_dot0"
                        android:layout_width="5dp"
                        android:layout_height="5dp"
                        android:layout_marginLeft="1.5dp"
                        android:layout_marginRight="1.5dp"
                        android:background="@drawable/dot_normal"/>

                -->

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


values/styles.xml

<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>
    
    <style name="dot_style">
	     <item name="android:layout_width">5dp</item>
	     <item name="android:layout_height">5dp</item>
	     <item name="android:background">@drawable/dot_normal</item>
	     <item name="android:layout_marginLeft">1.5dp</item>
	     <item name="android:layout_marginRight">1.5dp</item>
    </style>

</resources>

MainActivity.java

package com.example.myviewpage;

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.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
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.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

/**
 * 仿优酷Android客户端图片左右滑到 
 *
 */

public class MainActivity 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; //当前图片的索引号
	
	private ScheduledExecutorService scheduledExecutorService;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_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] = "八神庵,草稚京,阿k";  
        titles[2] = "草稚京";  
        titles[3] = "97拳王开始封面";  
        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(command, initialDelay, period, unit//单位)
	    scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 2, TimeUnit.SECONDS);
	    super.onStart();
	}

	// 暂停
	@Override
	protected void onStop() {
		//当Activity不可见的时候停止切换
		scheduledExecutorService.shutdown();
		super.onStop();
	}

	
    ///////////////////////////用Handler切换图片////////////////////////////////////////////////
	/**
	 * 换行切换任务-----子线程
	 * 
	 */
	private class ScrollTask implements Runnable{

		public void run() {  
                  synchronized (viewPager) {  
                  System.out.println("currentItem: " + currentItem);  
                  currentItem = (currentItem + 1) % imageViews.size();  
                  handler.obtainMessage().sendToTarget(); // 通过Handler切换图片  
            }  
        }  
  
	}
	
	 // 切换当前显示的图片
	 @SuppressLint("HandlerLeak")
	private Handler handler=new Handler(){

			public void handleMessage(android.os.Message msg) {
				
				//接收子线程的消息,处理
				viewPager.setCurrentItem(currentItem);// 切换当前显示的图片

			};
				
	 };
	  
	
    ///////////////////////////////////////////////////////////////////////////
		
		/**
		 * 当ViewPager中页面的状态发生改变时调用
		 * 
		 */
		private class MyPageChangeListener implements OnPageChangeListener{

			private int oldPosition=0;
			
			/**
			 * 页面滚动状态发生改变的时候触发
			 */
			@Override
			public void onPageScrollStateChanged(int arg0) {
				
			}

			/**
			 * 页面选中的时候触发
			 */
			// ---注意别用错方法---
			@Override
			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;
			}
			
			/**
			 * 页面滚动的时候触发
			 * 
			 */
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				
			}
			
		}
		
		
		/**
		 * 填充ViewPager页面的适配器
		 * 
		 */
		private class MyAdapter extends PagerAdapter{

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


			/**
			 * 从View集合中获取对应索引的元素,并添加到ViewPager中
			 */
			@Override
			public Object instantiateItem(View arg0, int arg1) {
				((ViewPager)arg0).addView(imageViews.get(arg1));
				return imageViews.get(arg1);
			}

			
			//销毁选项
			/**
	                 * 从ViewPager中删除集合中对应索引的View对象
	                 */
			@Override
			public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager)arg0).removeView((View)arg2);
			
			}
			
			/**
			 * 是否显示的ViewPager页面与instantiateItem返回的对象进行关联
			 */
			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				return arg0==arg1;
			}
			

			
			
		}
		
		

}




btn_back_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <!--获取焦点  -->
    <item android:state_focused="true" android:drawable="@drawable/btn_top_pressed" ></item>
    <!--按下  -->
    <item android:state_pressed="true" android:drawable="@drawable/btn_top_pressed" ></item>
    <!-- 选择时 -->
    <item android:state_selected="true" android:drawable="@drawable/btn_top_pressed" ></item>
    <!-- 默认 -->
    <item android:drawable="@drawable/title_bk"/> 
</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="5dp"/>

</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:startColor="#11264f"
        android:endColor="#009ad6"
        />
</shape>




ViewPager

标签:viewpager

原文地址:http://blog.csdn.net/u014558889/article/details/43816859

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!