Android ViewPage 实现图片左右滑动

步骤:

1、引入android-support-v4.jar包,在mian_activity.xml布局里加入 如下代码:

< ?xml version="1.0" encoding="utf-8"?>
< RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/layout"
tools:context="com.zjq.viewpager.MainActivity">

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

2、其他几个子布局都一样 例如 item01 :

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

< ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/view1"
    android:scaleType="centerCrop"
    />

3、编写Java代码:

public class MainActivity extends AppCompatActivity {

//查找布局文件用LayoutInflater.inflate
private LayoutInflater inflater;
//viewpager ID
private ViewPager viewpager;
//viewpager将view装入数组
private ArrayList pageview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    viewpager = (ViewPager)findViewById(R.id.vp_FindFragment_pager);


    // viewpager 查找布局文件用LayoutInflater.inflate
    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 view4 = inflater.inflate(R.layout.item04, null);

    //将分页显示的view装入数组
    pageview =new ArrayList();
    pageview.add(view1);
    pageview.add(view2);
    pageview.add(view3);
    pageview.add(view4);

    //  viewpPager数据适配器
    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);
} }
到这里就结束了。

你可能感兴趣的:(Android ViewPage 实现图片左右滑动)