Android:使用ViewPager實現左右滑動切換圖片 (簡單版)

ViewPager,它是google SDk中自帶的一個附加包的一個類, 可使視圖滑動。php

步驟:html

一、引入android-support-v4.jar包,在主佈局里加入android

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

二、加載切換內容數組

三、ViewPager加載適配器PagerAdapteride

public class MainActivity extends Activity {
private ViewPager viewPager;
private ArrayList<View> pageview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //設置無標題欄
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        setContentView(R.layout.main);
        
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        
        //查找佈局文件用LayoutInflater.inflate
        LayoutInflater inflater =getLayoutInflater();
        View view1 = inflater.inflate(R.layout.item01, null);
        View view2 = inflater.inflate(R.layout.item02, null);
        View view3 = inflater.inflate(R.layout.item03, null);
        
        //將view裝入數組
        pageview =new ArrayList<View>();
        pageview.add(view1);
        pageview.add(view2);
        pageview.add(view3);
        
        
        //數據適配器
        PagerAdapter mPagerAdapter = new PagerAdapter(){

            @Override
            //獲取當前窗體界面數
            public int getCount() {
                // TODO Auto-generated method stub
                return pageview.size();
            }

            @Override
            //斷是否由對象生成界面
            public boolean isViewFromObject(View arg0, Object arg1) {
                // TODO Auto-generated method stub
                return arg0==arg1;
            }
            //是從ViewGroup中移出當前View
             public void destroyItem(View arg0, int arg1, Object arg2) {  
                    ((ViewPager) arg0).removeView(pageview.get(arg1));  
                }  
            
            //返回一個對象,這個對象代表了PagerAdapter適配器選擇哪一個對象放在當前的ViewPager中
            public Object instantiateItem(View arg0, int arg1){
                ((ViewPager)arg0).addView(pageview.get(arg1));
                return pageview.get(arg1);                
            }
            
            
        };
        
        //綁定適配器
        viewPager.setAdapter(mPagerAdapter);

    }
}

>>>>>>>>>>>>>實例下載佈局

 相關文章:google

Android:ViewPager適配器PagerAdapter的使用spa

Android:使用ViewPager實現左右滑動切換圖片(圖上有點點)3d

相關文章
相關標籤/搜索