Making Great Android Viewpager Intro Screen With Page Transformer Animation

0
Shares
Making Great Android Viewpager Intro Screen With Page Transformer Animation
4.5 (90%) 2 votes

The Android viewpager has become quite popular among Android apps. It’s simple, neat, and intuitive.

Today, Developing apps isn’t just about writing code, providing features/functionalities. It is also about developing apps that users are comfortable using. Each individual should feel at home immediately after they launch your mobile app.

But how can one achieve this?

With Intro screen!

Now we understand that most of you might already have implemented standard Viewpager in your Android apps, but have you tried the page transformer?

By the way, have you read our Create an Intro Slider Screen in Your Android App That Attract New Audience Article?

The cool people have created this at Google. It is basically an interface that allows you to modify your intro screen slider animation. And this is not just a simple modification, you can create all sorts of awesome slide effects and animations!

Let’s Get Started

Create a new project in Android Studio.

Next, add a toolbar.

private Toolbar toolbar = null;

toolbar = (Toolbar) findViewById(R.id.toolbar);

setSupportActionBar(toolbar);

getSupportActionBar().setDisplayShowTitleEnabled(false);


//xml

<android.support.v7.widget.Toolbar

android:id="@+id/toolbar"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="?attr/colorPrimary"

android:minHeight="?attr/actionBarSize" />

 

Setting Up The Animation

  • Add spinner xml

Customizing spinner dropdown layout.

<?xml version="1.0" encoding="utf-8"?>

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

    android:id="@android:id/text1"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:background="@color/colorPrimary"

    android:gravity="center_vertical"

    android:minHeight="?android:attr/listPreferredItemHeightSmall"

    android:paddingLeft="12dp"

    android:paddingRight="12dp"

    android:textAppearance="?android:attr/textAppearanceListItemSmall"

    android:textColor="@android:color/white" />
  • Add Spinner in Toolbar to change animation

Screen1

 

screen2

 

final ArrayAdapter<TransformerItem> actionBarAdapter = new ArrayAdapter<TransformerItem>(

        getApplicationContext(), R.layout.spinner_dropdown, android.R.id.text1, TRANSFORM_CLASSES);

Spinner navigationSpinner = new Spinner(getSupportActionBar().getThemedContext());

navigationSpinner.setAdapter(actionBarAdapter);

toolbar.addView(navigationSpinner, 0);
  • Handling Spinner itemclick listner
//Set selected animation in viewpager

//viewPager.setPageTransformer

navigationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

    @Override

    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        mSelectedItem = position;

        try {

            viewPager.setPageTransformer(true, TRANSFORM_CLASSES.get(position).getClazz().newInstance());

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }

    @Override

    public void onNothingSelected(AdapterView<?> parent) {

    }

});

Start Code Integration

  • constants.java

(Get animation file from here)

public class Constants {

    public static final ArrayList<TransformerItem> TRANSFORM_CLASSES;

    static {

        TRANSFORM_CLASSES = new ArrayList<>();

        TRANSFORM_CLASSES.add(new TransformerItem(DefaultTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(AccordionTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(BackgroundToForegroundTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(CubeInTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(CubeOutTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(DepthPageTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(FlipHorizontalTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(FlipVerticalTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(ForegroundToBackgroundTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(RotateDownTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(RotateUpTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(ScaleInOutTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(StackTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(TabletTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(ZoomInTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(ZoomOutSlideTransformer.class));

        TRANSFORM_CLASSES.add(new TransformerItem(ZoomOutTranformer.class));

    }

}

 

  • TransformerItem
public class TransformerItem {

    final String title;

    final Class<? extends ViewPager.PageTransformer> clazz;

    public TransformerItem(Class<? extends ViewPager.PageTransformer> clazz) {

        this.clazz = clazz;

        title = clazz.getSimpleName();

    }

    public Class<? extends ViewPager.PageTransformer> getClazz() {

        return clazz;

    }

    @Override

    public String toString() {

        return title;

    }

}
  • Mainactivity.java
/*Deal with

*check preference value

* handle pager event by OnPageChangeListener

* view pager animation

*/

public class MainActivity extends AppCompatActivity {

    private ViewPager viewPager;

    private MyViewPagerAdapter myViewPagerAdapter;

    private LinearLayout dotsLayout;

    private TextView[] dots;

    private int[] layouts;

    private Button btnSkip, btnNext;

    private Prefs prefs;

    private Toolbar toolbar = null;

    private int mSelectedItem;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        // Checking for first time launch - before calling setContentView()

        prefs = Application.getApp().getPrefs();

        if (!prefs.isFirstTimeLaunch()) {

            launchHomeScreen();

            finish();

        }

        setContentView(R.layout.activity_main);

        initControls();

    }

    private void initControls() {

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

        dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);

        btnSkip = (Button) findViewById(R.id.btn_skip);

        btnNext = (Button) findViewById(R.id.btn_next);

        toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayShowTitleEnabled(false);

        initSpinner();

        initViewPagerControls();

    }

    private void initViewPagerControls() {

        // layouts of all welcome sliders

        // add few more layouts if you want

        layouts = new int[]{

                R.layout.welcome_screen1,

                R.layout.welcome_screen2,

                R.layout.welcome_screen3};

        // adding bottom dots

        addBottomDots(0);

        // making notification bar transparent

        changeStatusBarColor();

        myViewPagerAdapter = new MyViewPagerAdapter();

        viewPager.setAdapter(myViewPagerAdapter);

        viewPager.addOnPageChangeListener(viewPagerPageChangeListener);

        btnSkip.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                launchHomeScreen();

            }

        });

        btnNext.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                // checking for last page

                // if last page home screen will be launched

                int current = getItem(+1);

                if (current < layouts.length) {

                    // move to next screen

                    viewPager.setCurrentItem(current);

                } else {

                    launchHomeScreen();

                }

            }

        });

    }

    private void initSpinner() {

        final ArrayAdapter<TransformerItem> actionBarAdapter = new ArrayAdapter<TransformerItem>(

                getApplicationContext(), R.layout.spinner_dropdown, android.R.id.text1, TRANSFORM_CLASSES);

        Spinner navigationSpinner = new Spinner(getSupportActionBar().getThemedContext());

        navigationSpinner.setAdapter(actionBarAdapter);

        toolbar.addView(navigationSpinner, 0);

        navigationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override

            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                mSelectedItem = position;

                try {

                    viewPager.setPageTransformer(true, TRANSFORM_CLASSES.get(position).getClazz().newInstance());

                } catch (Exception e) {

                    throw new RuntimeException(e);

                }

            }

            @Override

            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

    }

    private void addBottomDots(int currentPage) {

        dots = new TextView[layouts.length];

        int[] colorsActive = getResources().getIntArray(R.array.array_pager_active);

        int[] colorsInactive = getResources().getIntArray(R.array.array_pager_inactive);

        dotsLayout.removeAllViews();

        for (int i = 0; i < dots.length; i++) {

            dots[i] = new TextView(this);

            dots[i].setText(Html.fromHtml("•"));

            dots[i].setTextSize(35);

            dots[i].setTextColor(colorsInactive[currentPage]);

            dotsLayout.addView(dots[i]);

        }

        if (dots.length > 0)

            dots[currentPage].setTextColor(colorsActive[currentPage]);

    }

    private int getItem(int i) {

        return viewPager.getCurrentItem() + i;

    }

    private void launchHomeScreen() {

        prefs.setFirstTimeLaunch(false);

        startActivity(new Intent(MainActivity.this, HomeActivity.class));

        finish();

    }

    //  viewpager change listener

    ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {

        @Override

        public void onPageSelected(int position) {

            addBottomDots(position);

            // changing the next button text 'NEXT' / 'GOT IT'

            if (position == layouts.length - 1) {

                // last page. make button text to GOT IT

                btnNext.setText(getString(R.string.start));

                btnSkip.setVisibility(View.GONE);

            } else {

                // still pages are left

                btnNext.setText(getString(R.string.next));

                btnSkip.setVisibility(View.VISIBLE);

            }

        }

        @Override

        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override

        public void onPageScrollStateChanged(int arg0) {

        }

    };

    /**

     * Making notification bar transparent

     */

    private void changeStatusBarColor() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            Window window = getWindow();

            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

            window.setStatusBarColor(Color.TRANSPARENT);

        }

    }

    /**

     * View pager adapter

     */

    public class MyViewPagerAdapter extends PagerAdapter {

        private LayoutInflater layoutInflater;

        public MyViewPagerAdapter() {

        }

        @Override

        public Object instantiateItem(ViewGroup container, int position) {

            layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View view = layoutInflater.inflate(layouts[position], container, false);

            container.addView(view);

            return view;

        }

        @Override

        public int getCount() {

            return layouts.length;

        }

        @Override

        public boolean isViewFromObject(View view, Object obj) {

            return view == obj;

        }

        @Override

        public void destroyItem(ViewGroup container, int position, Object object) {

            View view = (View) object;

            container.removeView(view);

        }

    }

}

 

  • Activity_main.xml

 

<?xml version="1.0" encoding="utf-8"?>

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

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar

        android:id="@+id/toolbar"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:background="?attr/colorPrimary"

        android:minHeight="?attr/actionBarSize" />

    <android.support.v4.view.ViewPager

        android:id="@+id/viewPager"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:layout_below="@+id/toolbar" />

    <LinearLayout

        android:id="@+id/layoutDots"

        android:layout_width="match_parent"

        android:layout_height="@dimen/dots_height"

        android:layout_alignParentBottom="true"

        android:layout_marginBottom="@dimen/dots_margin_bottom"

        android:gravity="center"

        android:orientation="horizontal"></LinearLayout>

    <View

        android:layout_width="match_parent"

        android:layout_height="1dp"

        android:layout_above="@id/layoutDots"

        android:alpha=".5"

        android:background="@android:color/white" />

    <Button

        android:id="@+id/btn_next"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentBottom="true"

        android:layout_alignParentRight="true"

        android:background="@null"

        android:text="@string/next"

        android:textColor="@android:color/white" />

    <Button

        android:id="@+id/btn_skip"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentBottom="true"

        android:layout_alignParentLeft="true"

        android:background="@null"

        android:text="@string/skip"

        android:textColor="@android:color/white" />

</RelativeLayout>

 

  • Spinner_dropdown.xml

 

<?xml version="1.0" encoding="utf-8"?>

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

    android:id="@android:id/text1"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:background="@color/colorPrimary"

    android:gravity="center_vertical"

    android:minHeight="?android:attr/listPreferredItemHeightSmall"

    android:paddingLeft="12dp"

    android:paddingRight="12dp"

    android:textAppearance="?android:attr/textAppearanceListItemSmall"

    android:textColor="@android:color/white" />

We are done!

Behold developers! We present you the output.

If you face any problem, you can contact our developers for help.

And if you don’t know, the page transformer interface is quite a powerful tool. With it, you can use your developing skills to create intriguing and intimidating intro screen sliders to make your Android app more delightful.

In case you’re not a technical person and wish to implement this feature in your Android app, you can hire Android app developer from us.

We’ve developed 2000+ mobile apps through our journey and being awarded for many times. You should check out our portfolio. And by hiring us you won’t just get an Android developer, but a separate dedicated team that solely focus on your project only. Contact us to know more.

Grab a free copy of Android viewpager pagetransformer demo from Github.

This page was last edited on November 21st, 2016, at 16:48.
 
0
Shares
 

Have an App Idea?

Get your free consultation now