Sunday, 1 September 2013

ViewPager Demo ( Without Fragments )

Demo: 
Devices =>2.3 & 4.2

1) MainActivity.java: 
package com.venky.viewpagerdemo;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;

public class MainActivity extends Activity {

       ViewPager view = null;

       int img[] = { R.drawable.apple, R.drawable.banana, R.drawable.lemon,
                    R.drawable.mango, R.drawable.pineapple };

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

             view = (ViewPager) findViewById(R.id.viewPager);

             view.setAdapter(new MyAdapter());
       }

       class MyAdapter extends PagerAdapter {

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

             @Override
             public Object instantiateItem(View container, int position) {
                    ImageView iv = new ImageView(MainActivity.this);
                    iv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                                 LayoutParams.MATCH_PARENT));
                    iv.setImageResource(img[position]);
                    ((ViewPager) container).addView(iv, 0);
                    return iv;
             }

             @Override
             public void destroyItem(View container, int position, Object obj) {
                    ((ViewPager) container).removeView((View) obj);
             }

             @Override
             public boolean isViewFromObject(View container, Object obj) {
                    return container == obj;
                    // return container == (View) obj;
             }

       }
}

2) activity_main.xml: 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:background="#5F04B4"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

</LinearLayout>

3) Download this Project Click Here

1 comment: