vxh.viet
7/11/2016 - 7:54 AM

View Pager without fragment

View Pager without fragment

Source: BigNerdRanch

Answer: demo simple ViewPager without using Fragment

TutorialActivity.java:

public class TutorialActivity extends AppCompatActivity {
    private static final int NUMBER_OF_PAGE = 5;
    private static final int DELAY_TIME = 2000; //time in milliseconds to automatically scroll to a new page
    private VideoView mVideoView;
    private ViewPager mViewPager;
    private TutorialPagerAdapter mPagerAdapter;
    private int mBackPressCount;


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

        mViewPager = (ViewPager)findViewById(R.id.tutorial_viewPager);
        mPagerAdapter = new TutorialPagerAdapter(this);
        mViewPager.setAdapter(mPagerAdapter);

        mVideoView = (VideoView)findViewById(R.id.tutorial_videoView);

        // setup indicator
        CircleIndicatorPager indicator = (CircleIndicatorPager)findViewById(R.id.tutorial_indicator);
        indicator.setRadius(12);
        indicator.setViewPager(mViewPager);

        RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.tutorial_container);
        relativeLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case(MotionEvent.ACTION_MOVE):
                        if(mTimer != null){
                            mTimer.cancel();
                        }
                        break;

                    case(MotionEvent.ACTION_UP):
                        autoScroll(0);
                        break;
                }
                return true;
            }
        });

        TextView loginTextView = (TextView)findViewById(R.id.tutorial_login);
        loginTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(TutorialActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }
                }, ShuttaConstants.ANIMATION_DELAY_TIME);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        setupVideo();
        autoScroll(DELAY_TIME);
    }

    private void setupVideo(){
        Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.intro_video);
        mVideoView.setVideoURI(uri);
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mVideoView.start();
            }
        });
    }

    // Auto Scroll stuff ---------------------------------------------------------------------------
    private Timer mTimer;
    private int mCurrentPage;

    private void autoScroll(long delayTimeForFirstExecution) {
        //mCurrentPage = 0;
        mTimer = new Timer(); // At this line a new Thread will be created
        mTimer.scheduleAtFixedRate(new RemindTask(), delayTimeForFirstExecution, DELAY_TIME); // delay in milliseconds
    }

    // this is an inner class...
    private class RemindTask extends TimerTask {
        @Override
        public void run() {

            // As the TimerTask run on a seprate thread from UI thread we have
            // to call runOnUiThread to do work on UI thread.
            runOnUiThread(new Runnable() {
                public void run() {
                    if (mCurrentPage > NUMBER_OF_PAGE) { // In my case the number of pages are 5
                        mTimer.cancel();
                        mCurrentPage = 0;
                        autoScroll(0);
                    } else {
                        mViewPager.setCurrentItem(mCurrentPage++, true);
                    }
                }
            });
        }
    }
    // End Auto Scroll stuff------------------------------------------------------------------------

    @Override
    protected void onStop() {
        super.onStop();
        if(mVideoView != null && mVideoView.isPlaying()){
            mVideoView.stopPlayback();
        }

        if(mTimer != null){
            mTimer.cancel();
        }
    }

    @Override
    public void onBackPressed() {
        mBackPressCount++;
        if (mBackPressCount >= 2) {
            finishAffinity();
        } else {
            Toast.makeText(this, "Press back again to quit", Toast.LENGTH_SHORT).show();
        }
    }
}

TutorialPagerEnum.java:

public enum TutorialPagerEnum {

    PAGE_1(R.string.tutorial_pager_page1 , R.layout.item_pager_tutorial_page1),
    PAGE_2(R.string.tutorial_pager_page2 , R.layout.item_pager_tutorial_page2),
    PAGE_3(R.string.tutorial_pager_page3 , R.layout.item_pager_tutorial_page3),
    PAGE_4(R.string.tutorial_pager_page4 , R.layout.item_pager_tutorial_page4),
    PAGE_5(R.string.tutorial_pager_page5 , R.layout.item_pager_tutorial_page5);

    private int mTitleResId;
    private int mLayoutResId;

    TutorialPagerEnum(int titleResId, int layoutResId) {
        mTitleResId = titleResId;
        mLayoutResId = layoutResId;
    }

    public int getTitleResId() {
        return mTitleResId;
    }

    public int getLayoutResId() {
        return mLayoutResId;
    }
}

TutorialPagerAdapter.java:

public class TutorialPagerAdapter extends PagerAdapter {

    private Context mContext;

    public TutorialPagerAdapter(Context context) {
        mContext = context;
    }

    @Override
    public Object instantiateItem(ViewGroup collection, int position) {
        TutorialPagerEnum customPagerEnum = TutorialPagerEnum.values()[position];
        LayoutInflater inflater = LayoutInflater.from(mContext);
        ViewGroup layout = (ViewGroup) inflater.inflate(customPagerEnum.getLayoutResId(), collection, false);
        collection.addView(layout);
        return layout;
    }

    @Override
    public void destroyItem(ViewGroup collection, int position, Object view) {
        collection.removeView((View) view);
    }

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

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        TutorialPagerEnum tutorialPagerEnum = TutorialPagerEnum.values()[position];
        return mContext.getString(tutorialPagerEnum.getTitleResId());
    }
}

activity_tutorial_video.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:app="http://schemas.android.com/apk/res-auto"
       android:id="@+id/tutorial_container"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical">

    <VideoView
        android:id="@+id/tutorial_videoView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"/>

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

    <ImageView
        android:id="@+id/tutorial_logo"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="@dimen/tutorial_logo_margin_top"
        android:src="@drawable/tutorial_main_logo"/>

    <co.shutta.shuttapro.widgets.CircleIndicatorPager
        android:id="@+id/tutorial_indicator"
        android:layout_width="match_parent"
        android:layout_height="@dimen/tutorial_indicator_height"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="@dimen/tutorial_indicator_margin_bottom"
        android:padding="5dp" />
    
    <TextView
        android:id="@+id/tutorial_login"
        android:layout_width="wrap_content"
        android:layout_height="@dimen/tutorial_login_signup_height"
        app:layout_widthPercent="50%"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="@string/login"
        android:gravity="center"
        android:textSize="@dimen/tutorial_login_signup_text_size"
        android:textColor="@color/white_tint_1"
        android:textAllCaps="true"
        android:textStyle="bold"
        android:background="@drawable/ripple_effect_login"
        android:clickable="true"
        />

    <TextView
        android:id="@+id/tutorial_signup"
        android:layout_width="wrap_content"
        android:layout_height="@dimen/tutorial_login_signup_height"
        app:layout_widthPercent="50%"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="@string/signupBtn"
        android:gravity="center"
        android:textSize="@dimen/tutorial_login_signup_text_size"
        android:textColor="@color/white_tint_1"
        android:textAllCaps="true"
        android:textStyle="bold"
        android:background="@drawable/ripple_effect_signup"
        android:clickable="true"
        />

</android.support.percent.PercentRelativeLayout>

For CircleIndicatorPager see part 1

item_pager_tutorial_page1 (similar for page 2, 3, 4, 5):

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

    <ImageView
        android:layout_width="400dp"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="@dimen/tutorial_text_margin_bottom"
        android:src="@drawable/page1_text"/>
</RelativeLayout>

Sample dimens:

    <dimen name="tutorial_logo_margin_top">20dp</dimen>
    <dimen name="tutorial_indicator_height">64dp</dimen>
    <dimen name="tutorial_indicator_margin_bottom">72dp</dimen>
    <dimen name="tutorial_text_width">250dp</dimen>
    <dimen name="tutorial_text_margin_bottom">130dp</dimen>
    <dimen name="tutorial_login_signup_height">56dp</dimen>
    <dimen name="tutorial_login_signup_text_size">18sp</dimen>