--ADVERTISEMENT--

Animated gradient background can be implemented in android app easily using XML and java code. Moving gradients background between different two or more gradients as animation makes your app more awesome. You may see this type of background color animation in instagram app. Instagram app keeps transforming background from one gradient to another beautifully.

You can easily add transforming gradients background in your android app easily using animation list. In this tutorial, you will learn to make moving gradient background in android using XML animator list and java code. You can add animation differently in android app but here we will show you one easiest way to add animation to your gradient background using XML.

Related:
Chat/Messaging App XML UI Design for Android
Drag and Drop Android Example
Simple Android Calculator App XML UI Design

How to Implement Transition Background Gradient

Animated Gradient Background in Android

First let’s start by creating new android project Animated Gradient Android as app name & viralandroid.com as company domain and rest of all things leave default.

Android Gradient Drawables

Now we will create different gradient drawables with different color and file name. Here we create gradient_1.xml, gradient_2.xml and gradient_3.xml XML drawable files with gradient attributes android:angle, android:endColor and android:startColor. Following is the XML code of three drawable files.

res/drawable/gradient_1.xml


res/drawable/gradient_2.xml



res/drawable/gradient_3.xml


Now create a new XML drawable file android_gradient_list.xml and add the following code which contains the AnimationList, which is responsible to change the background color from one gradient to another. In the AnimationList tag, add 3 items and referring to the above 3 XML drawable files.

res/drawable/android_gradient_list.xml


XML Layout File

Open your app main XML layout file activity_main.xml and set background to the root layout (View or ViewGroup) of the activity where you want to add animated gradient background. Also give an id to that layout; we will need to refer in java activity file.

res/layout/activity_main.xml


Java Activity File

In java activity file you need to tell the animation list to start moving transaction using AnimationDrawer.start methoad and animationDrawable.setEnterFadeDuration, animationDrawable.setExitFadeDuration and .getBackground.

src/MainActivity.java


Animated Gradient Background in Android

Animated Gradient Background in Android

Animated Gradient Background in Android

Now, run your app by clicking run button. You will see the animation between background gradient with different color like above screenshots.

Android 7.0 Nougat brings support for more than one application open and run at the same time. This is not the new concept because Samsung’s been doing it earlier, Microsoft and even Apple is doing it already. Now it comes on all Android devices running 7.0 and higher version. In this tutorial, you will learn to make your app working as split screen mode, picture in picture mode, and freeform screen mode.

Switch to multi screen mode; open an app on your device and long press the overview button, drag the app to one side of your screen to put the activity in multi-window mode. Multi-window mode is one of the awesome features that has blessed large android devices. It lets you to easily complete multiple tasks on same single screen dividing in to different parts. You can write something in notes app by watching YouTube video or news etc.

Related:
Android Drag Select RecyclerView Library
Facebook Integration in Android - Facebook Login
Adding a Share Action to Android Application

Android 7.0 Nougat: Split-Screen Mode, Picture-in-picture Mode and Freeform Mode



Android Multi Window Split Screen and Freedom Tutorial


Let’s start by creating new android project with Multi Window App Development app name and viralandroid.com as company domain. Select the minimum SDK to Android N.

First Activity User Interface


Open activity_main.xml layout file from res> layout and add a Button and a TextView inside ConstraintLayout. Your root layout is ConstraintLayout (android.support.constraint.ConstraintLayout). TextView contain default text Hello World! And Button contain onClick attribute and text Start.

First Activity User Interface

Main activity XML layout source code

res/layout/activity_main.xml

Second Activity User Interface


Add new activity XML layout by right clicking on the layout and enter the XML layout name for second activity; activity_second.xml. Second activity will be lunched when the user clicks on the button in first activity. In second activity of XML layout file we will add only a TextView inside LinearLayout. Following is the XML code of second activity.

res/layout/activity_second.xml



Java Code for MainActivity.java and SecondActivity.java File


Launch second activity from first activity when Start button is clicked. Here we add i.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT |Intent.FLAG_ACTIVITY_MULTIPLE_TASK |Intent.FLAG_ACTIVITY_NEW_TASK); and Rect rt = new Rect(0, 0, 100, 100) ActivityOptions actoptions = ActivityOptions.makeBasic(); ActivityOptions bounds = actoptions.setLaunchBounds(rt); Following is the complete source code of main activity file.


src/MainActivity.java

And default java code of second activity is looks like below:

src/SecondActivity.java


AndroidManifest.xml File


Inside MainActivity of Android Manifest file add android:resizeableActivity="true" and define activity second below first activity which is looks like below:

AndroidManifest.xml

And finally build.gradle file looks like this:

Android Multi Window Split Screen and Freedom Tutorial

Now run app by clicking run button. Switch into multi window mode. To switch into multi window mode long press on the overview button and drag the app to one side of the screen, which looks like below screenshots.

Ripple effect or animation can be added in android layouts, buttons, textviews, etc. You can change ripple color and shape like circular, rectangle. By default, ripple effect is only shown on device running lollipop and above, but using third party library, you can implement ripple animation on all android versions.

In this post, I have mentioned some best and useful android ripple effect libraries which will help you to make awesome material design. There are many libraries available but here, I have only listed some of the best libraries for you.

Related:
Android XML Animations Examples
Android Bottom/Footer Menu Example with SlideUp Animation
Animated Android Toolbar With Appbar Background Image


5 Best Android Ripple Effect Libraries

Here are the best 5 android ripple effect library for your awesome app or game. You can easily implement these libraries in any android app. Some of these work only for Android 21+ and other 9 & above.

1. RippleEffect

Implementation of Ripple effect from Material Design for Android API 9+. ExpandableLayout provides an easy way to create a view called header with an expandable view. Both views are external layout to allow a maximum of customization. You can find a sample that how to use an ExpandableLayout to your layout.

Best Android Ripple Effect Libraries


Dependencies

dependencies {
    compile 'com.github.traex.rippleeffect:library:1.3'
}

Usage

Declare a RippleView inside your XML layout file with content like an ImageView or whatever.

<com.andexert.library.RippleView
  android:id="@+id/more"
  android:layout_width="?android:actionBarSize"
  android:layout_height="?android:actionBarSize"
  android:layout_toLeftOf="@+id/more2"
  android:layout_margin="5dp"
  rv_centered="true">

  <ImageView
    android:layout_width="?android:actionBarSize"
    android:layout_height="?android:actionBarSize"
    android:src="@android:drawable/ic_menu_edit"
    android:layout_centerInParent="true"
    android:padding="10dp"
    android:background="@android:color/holo_blue_dark"/>

</com.andexert.library.RippleView>

If you want to know when the Ripple effect is finished, you can set a listener on your view

    rippleView.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
        @Override
        public void onComplete(RippleView rippleView) {
            Log.d("Sample", "Ripple completed");
        }

    });

If you want to add an OnClickListener don't forget to add it to the RippleView like this:

    final RippleView rippleView = (RippleView) findViewById(R.id.rippleView);
    rippleView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //TODO: onRippleViewClick
        }
    });


Get RippleEffect Library Source Code On GitHub

2.  RippleView

View that imitates Ripple Effect on click which was introduced in Android L (for Android 2.3+)

Best Android Ripple Effect Libraries


Usage

For a working implementation, have a look at the Sample Project - RippleViewExample
1. Include the library as local library project.
2. Include the RippleView widget in your layout.
3. In your onCreate method refer to the View and add 'OnClickListener' for the same.

mButton = (RippleView) findViewById(R.id.btn);
mButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //your code
    }
});

Get RippleView Library Source Code On GitHub

3. Material Ripple Layout

Android L Ripple effect wrapper for Views

Dependencies

compile 'com.balysv:material-ripple:1.0.2'

Best Android Ripple Effect Libraries


Usage

Use static initializer on your View (see xml attributes below for customization)

MaterialRippleLayout.on(view)
           .rippleColor(Color.BLACK)
           .create();

Or wrap your View with MaterialRippleLayout in your layout file:

<com.balysv.materialripple.MaterialRippleLayout
    android:id="@+id/ripple"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Button inside a ripple"/>

</com.balysv.materialripple.MaterialRippleLayout>

If using in an AdapterView you must set rippleInAdapter to true

Configure using xml attributes or setters in code:

app:mrl_rippleOverlay="true"
app:mrl_rippleColor="#ff0000"
app:mrl_rippleAlpha="0.1"
app:mrl_rippleDimension="10dp"
app:mrl_rippleHover="true"
app:mrl_rippleRoundedCorners="10dp"
app:mrl_rippleInAdapter="true"
app:mrl_rippleDuration="350"
app:mrl_rippleFadeDuration="75"
app:mrl_rippleDelayClick="true"
app:mrl_rippleBackground="#FFFFFF"
app:mrl_ripplePersistent="true"

Get Material Ripple Layout Library Source Code On GitHub

4. Google Maps Animations

Google Maps Animations is an awesome first of its type android library for showing a ripple and radar animations on a google map, e.g show catchment area of an earthquake where ripples have been felt, give prominence to certain markers which need to be highlighted. Also add a ripple when your user is moving on the map and give a #PokemonGo type ripple effect and also add a radar type effect to show users that you are searching in certain area.

Best Android Ripple Effect Libraries


Dependencies
compile 'com.github.aarsy.googlemapsanimations:googlemapsanimations:1.0.5'

Get Google Maps Animations Library Source Code On GitHub

5. Ripple Layout

A layout that implemented ripple effect for transition animation. A ripple is not just a circle that starts expanding from your finger till it covers all the view. In fact, the circle starts expanding from your finger while its center travels to the center of the view with a fixed speed. By the time the circle's center has reached the center of the view its radius will be equal to the distance between the view's center and its farthest edge. In this way, the ripple reaches every edge of the view at almost the same time.

Best Android Ripple Effect Libraries


Dependencies

dependencies {
    compile 'com.liuguangqiang.ripplelayout:library:0.1.0'
}

Start Activity

The ripple animation can start from a Point or a View. But the transition animation of the target activity must be implemented by yourself.

Ripple.startActivity(MainActivity.this, TargetActivity.class, A point or a view);

Get RippleEffect Library Source Code On GitHub

If there are other best libraries except above mentioned, you can add them in the comment box.

Previously, for transitions between different activities and fragments for enter and exit transitions, we used fade animation, slide animation or any other animation. A shared element transitions determines how shared element views are animated from one activity to another activity or fragment to fragment. A share element transition helps users to go different screens through your app by defining a focal point as they go different screens.

This share element transitions is only available on android lollipop and above (API level 21+). In this tutorial, you will learn to implement a kind of animation transition, Share Element transitions between different activities. You can implement it between Fragments, RecyclerView and so on.

Related:
Android Material Design GridView
Sending Email from Android Application
Adding a Share Action to Android Application

Shared Element Transitions: Activity to Activity Example

Shared Element Activity Transitions in Android


Here we are going to create two different activities MainActivity and ActivityTwo. First activity contains an image and a button. When button is clicked the new activity ActivityTwo is launch. This second activity loaded everything about transitions. Second activity contains everything that you want to show to the user, In this example I will show a image in ImageView and text in TextView.

Let’s start by creating new android project to implement shared element transitions between activity to activity in android app.
Application Name: Android Shared Element Transitions
Company Domain: viralandroid.com
API Level: 21+
Activity: Empty Activity

Enable Window Content Transitions

First you need to enable window content transitions. For that open your styles.xml file and add android:windowContentTransitions true.

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="android:windowContentTransitions">true</item>
    </style>
</resources>

XML Layout File


Open your activity_main.xml file and add an ImageView with id, layout_width, layout_height, src, transitionName, etc. and a Button with an id, layout_width, layout_height, text and so on. Your activity_main.xml file will look like below.

res/layout/activity_main.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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.viralandroid.sharedelementtransitions.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="128dp"
        android:layout_height="96dp"
        android:layout_above="@+id/button_start_new_activity_transaction"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="30dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/ic_launcher"
        android:transitionName="simple_activity_transition" />

    <Button
        android:id="@+id/button_start_new_activity_transaction"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Click" />

</RelativeLayout>

Now create a new XML layout file called simple_transaction_activity_layout.xml and add an ImageView & a TextView.

res/layout/simple_transaction_activity_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">

    <ImageView
        android:id="@+id/simple_activity_b_image"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/ic_launcher"
        tools:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/transaction_activity_two"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="The transitionName has to be unique on the screen to any other element transitions you have. Otherwise you’ll just confuse the framework and may get some weird results. A shared element transition determines how shared element views—also called hero views—are animated from one Activity/Fragment to another during a scene transition. Shared elements are animated by the called Activity/Fragment’s enter and return shared element transitions." />
</LinearLayout>

Android Java Activities File

Open your MainActivity.java file and define ImageView, Button and so on. Screen transitions animation is implementing inside on button click listener.



src/MainActivity.java



Now create a new java activity file called ActivityTwo.java. Here you don’t need to do any more things just in setContentView to the second XML layout file.

src/ActivityTwo.java




AndroidManifest.xml File

AndroidManifest.xml file will look like below:



Now, run your Android Shared Element Transitions app by clicking run icon. After launching your app, click the button, there will open a new screen with animation effect. This animation effect can be seen when you come back to previous activity. If you want to know more details about this you can found here, a article by Mike Scamell.

Facebook Audience Network is a mobile advertising machine. It allows you to monetize your Android or IOS apps with facebook ads. You can monetize with facebook native ads, banner ads, interstitial ads and in-stream video ads. In this tutorial, you will learn to integrate facebook audience network SDK in android application and display facebook ads in your app.

You may see different types of facebook ads on instagram and facebook app. But now, facebook allows displaying their ads on other apps and mobile websites through Facebook Audience Network.

Related:
Facebook Integration in Android - Facebook Login
How to Integrate Google AdMob in Android
Integrating Google Firebase Analytics to your Android Project

Create a New Android Project

Let’s start by creating a new android project. Open Android Studio and create a new android project with app name “Facebook Audience Network Tutorial”, company domain “viralandroid.com”, set your minimum SDK version to API 15 or higher.

Facebook Audience Network Android SDK Integration


Add Facebook Audience Network Dependencies

Open your app level build.gradle file and add the following dependencies.

dependencies {
  ...
  compile 'com.facebook.android:audience-network-sdk:4.+'
}


Configure Your AndroidManifest.xml File

You need to add the INTERNET and ACCESS_NETWORK_STATE permissions and include AudienceNetworkActivity under the application element:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.viralandroid.facebookaudiencenetworktutorial">
  ...
<uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

      <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
    ...
    <activity android:name="com.facebook.ads.AudienceNetworkActivity"
        android:configChanges="keyboardHidden|orientation|screenSize" />
    ...
  </application>
  ...
</manifest>

Configure Your App on Facebook

Go to facebook audience network page (https://developers.facebook.com/docs/audience-network), log in with your facebook account.

Facebook Audience Network Android SDK Integration

Click start button and create new facebook app or choose existing one.

Configure Ad Placements

1. Navigate to your app’s Audience Network setting.
2. In the Placement section, click Create Ad Placement

Facebook Audience Network Android SDK Integration


3. Give a name, step to trigger ad, choose display format.  The bottom slider allows you to optimize ad pricing for this placement. In most cases, Optimize for Fill will yield the highest revenue. Selecting Optimize for CPM will give higher price per impression but will reduce the fill rate. This may be the right setting if you are using mediation with multiple demand sources and are less concerned about unfilled requests.

4. Click Save to save your placement configuration.

Integrate Facebook Native Ad in Android

Facebook Native Ads allows you to build a customized UI for the ads you show in your app. You can customize and receive ad properties such as a title, an image, a call to action and so on.

Requesting a Facebook Native Ad in Android

Import the facebook ads SDK at the top of your activity:

import com.facebook.ads.*;

Create Your Native Ad Layout

Open your XML layout file and add a container for your Native Ad, Your XML layout file code will look like below.

res/layout/activity_main.xml


Create a custom native ad layout with name custom_native_ad_layout.xml. Your custom native ad layout code will look like below.

res/layout/custom_native_ad_layout.xml


Modifying Your App Java Activity File

Open your java activity file and then, instantiate a NativeAd object, set an AdListener, and call loadAd(). Following is the complete code for your java activity file:

src/MainActivity.java


Change NativeAd id with your ad unit. You will get ad unit under Audience Network > Placements.

Facebook Audience Network Android SDK Integration

Now run your Facebook Audience Network example project by clicking run button from menu bar. After running your app, you will see facebook ad in your app, which will look like above screenshot.

Download Complete Example Project

You can download complete Facebook Audience Network Android SDK Integration example project from GitHub.

The android hardware and system information is different from device to device. You can find your android device info manually in About device section of settings. In this tutorial, you will learn to get android device system and hardware information programmatically. We will focus on some of the properties like serial number, model no, id, android SDK, brand, manufacture, version code, etc.

There are many other info you can get from a android device but here we will focus on some of the android properties. To get system info, we are going to add a button and a textview to display information of android device when button is clicked.

Related:
Embed and Play MP3 Songs/Music in Android Application Using WebView
Android Custom Horizontal Icons Menu
Material Ripple Effect/Animation in Android

There are different methods to retrieve the platform related information of the device programmatically. To obtain the hardware and software related information of an android device that runs your application, follow the following steps. Here we will only display information in TextView but you can also track to your server. You can get info like;


  • CPU Manufacturer
  • Model and serial number
  • SD Card Manufacturer
  • Camera Manufacturer and other related specs
  • Bluetooth related information
  • WiFi related information
  • Display vendor and model


How to Get Android Hardware and System Information Programmatically

Android Example: Getting Android Hardware and System Information Programmatically

Create a new android project with project name AndroidSystemInfo packagecom.viralandroid.androidsysteminfo.

XML Layout File

Open your activity_main.xml file and add a Button and TextView with different id. TextView is used to display device info when we click the button. Following is the complete code XML layout file.

res/layout/activity_main.xml


Java Activity File

Open your MainActivity.java activity file and define button and textview that we have created above in xml layout file. To get and display system info, see the following code.

src/MainActivity.java


And colors.xml, styles.xml file will look like below;

res/values/colors.xml


res/values/styles.xml


You have done all things. Now, run your application by clicking run button and click Get Android System Info button; you will see all information below the button like the screenshot presented above.

Steppers convey progress through numbered steps. Steppers display progress through a sequence of logical and numbered steps. They may also be used for navigation. Steppers may display a transient feedback message after a step is saved.

This library allows to use Material steppers inside Android applications. Steppers display progress through a sequence by breaking it up into multiple logical and numbered steps.

Types of Steps:
- Editable
- Non-editable
- Mobile
- Optional

Types of Steppers:
- Horizontal
- Vertical
- Linear
- Non-linear

Related:
Android AppIntro Slider Example
Android XML Animations Examples
Android Push Notification Tutorial Using Firebase

Supported features:

Color customisation of individual widgets inside of the stepper via View attributes or a style from a theme
Custom texts of individual widgets inside of the stepper via View attributes or a style from a theme
Embedding the stepper anywhere in the view hierarchy and changing the stepper type for various device configurations, e.g. phone/tablet, portrait/landscape
Step validation
Use with Fragments or Views

Android Material Stepper Library Tutorial and Source Code


Getting started

Android Dependencies:

compile 'com.stepstone.stepper:material-stepper:2.2.0'

Create layout in XML

<?xml version="1.0" encoding="utf-8"?>
<com.stepstone.stepper.StepperLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/stepperLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:ms_stepperType="progress_bar" />


Create step Fragment(s)

Step fragments must extend android.support.v4.app.Fragment and implement com.stepstone.stepper.Step

public class StepFragmentSample extends Fragment implements Step {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.step, container, false);

        //initialize your UI

        return v;
    }

    @Override
    public VerificationError verifyStep() {
        //return null if the user can go to the next step, create a new VerificationError instance otherwise
        return null;
    }

    @Override
    public void onSelected() {
        //update UI when selected
    }

    @Override
    public void onError(@NonNull VerificationError error) {
        //handle error inside of the fragment, e.g. show error on EditText
    }

}

Extend AbstractFragmentStepAdapter

AbstractFragmentStepAdapter extends FragmentPagerAdapter but instead of overriding the method getItem(int) you must override the createStep(int) method.

public static class MyStepperAdapter extends AbstractFragmentStepAdapter {

    public MyStepperAdapter(FragmentManager fm, Context context) {
        super(fm, context);
    }

    @Override
    public Fragment createStep(int position) {
        final StepFragmentSample step = new StepFragmentSample();
        Bundle b = new Bundle();
        b.putInt(CURRENT_STEP_POSITION_KEY, position);
        step.setArguments(b);
        return step;
    }

    @Override
    public int getCount() {
        return 3;
    }

    @NonNull
    @Override
    public StepViewModel getViewModel(@IntRange(from = 0) int position) {
        //Override this method to set Step title for the Tabs, not necessary for other stepper types
        return new StepViewModel.Builder(context)
                .setTitle(R.string.tab_title) //can be a CharSequence instead
                .create();
    }
}

Set adapter in Activity

public class StepperActivity extends AppCompatActivity {

    private StepperLayout mStepperLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mStepperLayout = (StepperLayout) findViewById(R.id.stepperLayout);
        mStepperLayout.setAdapter(new MyStepperAdapter(getSupportFragmentManager(), this));
    }
}

Add a StepperListener in the Activity (optional)

public class StepperActivity extends AppCompatActivity implements StepperLayout.StepperListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //...
        mStepperLayout.setListener(this);
    }

    @Override
    public void onCompleted(View completeButton) {
        Toast.makeText(this, "onCompleted!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(VerificationError verificationError) {
        Toast.makeText(this, "onError! -> " + verificationError.getErrorMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onStepSelected(int newStepPosition) {
        Toast.makeText(this, "onStepSelected! -> " + newStepPosition, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onReturn() {
        finish();
    }

}

Change Next/Complete button's text color when going to the next step should be disabled (optional)

It is possible to change the Next/Complete button's text color (together with right chevron's color) when all the criteria to go to the next step are not met. This color should indicate that the user cannot go to next step yet and look as if disabled. Clicking on the button will still perform the regular step verification. There is a custom state added since setting android:state_enabled to false in a color selector would disable the clicks and we want to have them so that we can show an info message for the user. In order to set that color:

Create a new color selector in res/color

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
    <item app:state_verification_failed="true" android:color="#30BDBDBD"/>
    <item android:color="@color/ms_white"/>
</selector>

Change button's (text) color in layout file

<?xml version="1.0" encoding="utf-8"?>
<com.stepstone.stepper.StepperLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/stepperLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:ms_stepperType="dots"
    app:ms_nextButtonColor="@color/ms_custom_button_text_color"
    app:ms_completeButtonColor="@color/ms_custom_button_text_color" />

Toggle the state in code

mStepperLayout.setNextButtonVerificationFailed(!enabled);
mStepperLayout.setCompleteButtonVerificationFailed(!enabled);
Make an IO operation before going to the next step (optional)

If the user wants to e.g. save something in the database or make a network call on a separate Thread after clicking on the Next button he can perform these operations and then invoke the goToNextStep() method of the StepperLayout.OnNextClickedCallback in the current Step. While operations are performed, and the user would like to go back you can cancel them and then invoke onBackClicked() method of the StepperLayout.OnBackClickedCallback.

The fragment must implement BlockingStep instead of Step. Also, make sure that goToNextStep() gets called on the main thread. Note: the onNextClicked(StepperLayout.OnNextClickedCallback) method gets invoked after step verification. E.g.:

public class DelayedTransitionStepFragmentSample extends Fragment implements BlockingStep {

    //...

    @Override
    @UiThread
    public void onNextClicked(final StepperLayout.OnNextClickedCallback callback) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                callback.goToNextStep();
            }
        }, 2000L);
    }

    @Override
    @UiThread
    public void onBackClicked(StepperLayout.OnBackClickedCallback callback) {
        Toast.makeText(this.getContext(), "Your custom back action. Here you should cancel currently running operations", Toast.LENGTH_SHORT).show();
        callback.goToPrevStep();
     }

}

Changing Back/Next button labels per step

Sometimes you might want to have different labels on the Next and/or Back navigation buttons on different steps e.g. use the default labels on the first few steps, but display 'Summary' just before the last page.


In such case you need to override the getViewModel(int) method from the StepAdapter e.g.

    @NonNull
    @Override
    public StepViewModel getViewModel(@IntRange(from = 0) int position) {
        StepViewModel.Builder builder = new StepViewModel.Builder(context)
                .setTitle(R.string.tab_title);
        switch (position) {
            case 0:
                builder
                        .setNextButtonLabel("This way")
                        .setBackButtonLabel("Go to first");
                break;
            case 1:
                builder
                        .setNextButtonLabel(R.string.go_to_summary)
                        .setBackButtonLabel("Go to first");
                break;
            case 2:
                builder.setBackButtonLabel("Go back");
                break;
            default:
                throw new IllegalArgumentException("Unsupported position: " + position);
        }
        return builder.create();
    }

Using the same stepper styling across the application

If you have many steppers in your application in different activities/fragments you might want to set a common style in a theme. To do so, you need to set the ms_stepperStyle attribute in the theme, e.g.

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        ...

        <item name="ms_stepperStyle">@style/DotStepperStyle</item>
    </style>

and declare that style in the XML you keep your styles at, e.g.

    <style name="DotStepperStyle">
        <item name="ms_stepperType">dots</item>
        <item name="ms_activeStepColor">#FFFFFF</item>
        <item name="ms_inactiveStepColor">#006867</item>
        <item name="ms_bottomNavigationBackground">?attr/colorAccent</item>
    </style>

Showing a Back button on first step

By default if the user is on the first step then the Back button in the bottom navigation is hidden. This behaviour can be changed by setting ms_showBackButtonOnFirstStep to true, e.g.

    <?xml version="1.0" encoding="utf-8"?>
    <com.stepstone.stepper.StepperLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/stepperLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:ms_showBackButtonOnFirstStep="true"
        app:ms_stepperType="dots" />

To get a callback when this button was pressed you need set a StepperListener and write your own custom return logic in the onReturn() method to e.g. close the Activity.

Using with Views instead of Fragments

It is possible to use this library without the need to rely on Fragments. To do so you need to use AbstractStepAdapter instead of AbstractFragmentStepAdapter. For an example of how to use it with views please see the sample app.

Custom styling

Basic styling can be done by choosing the active and inactive step colors. There are some additional properties which can be changed directly from StepperLayout's attributes e.g. the background of bottom navigation buttons (see StepperLayout attributes) For advanced styling you can use ms_stepperLayoutTheme StepperLayout's attribute and provide your custom style to be used. See 'Custom StepperLayout theme' in the sample app for an example.

Advanced usage

For other examples, e.g. persisting state on rotation, displaying errors, changing whether the user can go to the next step, etc. check out the sample app.

Download Complete Source Code

Github: https://github.com/stepstone-tech/android-material-stepper
Powered by Blogger.