Android & Kotlin

Build Intro Slider in Android

Pinterest LinkedIn Tumblr

In this post, I’m going to explain how to build intro slider in an android step by step. We’ll learn why we should use intro slider in android? we’ll talk about benefits, uses, and the real implementation of Intro Slider Let’s get started.

Why Intro Slider Screen?

Make sure first-time users should be aware of the functions and benefits of the app while coming on the app. Intro slider screen is very essential for Introducing first-time users to your app. It is a virtual unique interaction that helps users get started with an app.

Intro slider android example app
1. Setup a new android project

Open the Android Studio and create a new android project. In this project navigate app build.gradle add material io dependencies.

implementation 'com.google.android.material:material:1.2.0-alpha01'
2. Open activity_main.xml and paste below code

This layout file contains ViewPager and TabLayout. TabLayout we are using for dot indicator

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity"
    >

  <androidx.viewpager.widget.ViewPager
      android:id="@+id/pagerIntroSlider"
      android:layout_width="0dp"
      android:layout_height="0dp"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintHorizontal_bias="0.0"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      app:layout_constraintVertical_bias="1.0"
      />

  <com.google.android.material.tabs.TabLayout
      android:id="@+id/tabs"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginBottom="8dp"
      app:layout_constraintBottom_toTopOf="@+id/button"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:tabBackground="@drawable/slider_dot_selector"
      app:tabGravity="center"
      app:tabIndicatorHeight="0dp"
      />


  <Button
      android:id="@+id/button"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:background="@drawable/ic_button_bg"
      android:text="@string/next"
      android:textColor="@color/colorWhite"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      />
</androidx.constraintlayout.widget.ConstraintLayout>
2.1 Prepare drawable dot selector slider
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/slider_selected_dot"
      android:state_selected="true"/>
  <item android:drawable="@drawable/slider_unselected_dot"/>
</selector>
2.2 Now create a drawable file named is slider_selected_dot.xml for a selected dot.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape
        android:innerRadius="0dp"
        android:shape="ring"
        android:thickness="5dp"
        android:useLevel="false">
      <solid android:color="#ffffff"/>
    </shape>
  </item>
</layer-list>
2.3 Furthermore create one more drawable file for unselected dot is named slider_unselected_dot
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:innerRadius="0dp"
        android:shape="ring"
        android:thickness="5dp"
        android:useLevel="false">
      <solid android:color="@android:color/transparent" />
      <stroke
          android:width="1dp"
          android:color="#C1FFFFFF" />
    </shape>
  </item>
</layer-list>
2.4 Few more res file need such as image and string.

Open strings.xml and paste below code

<resources>
  <string name="app_name">Intro Slider App</string>
  <string name="next">Next</string>
  <string name="discover">Discover</string>
  <string name="shop">Shop</string>
  <string name="offers">Offers</string>
  <string name="rewards">Rewards</string>
  <string name="discover_text">Look for things around you</string>
  <string name="shop_text"><![CDATA[Get the best deals & Coupons]]></string>
  <string name="offers_text">Find great offers while you discover</string>
  <string name="rewards_text"><![CDATA[Free recharge coupons & more]]></string>
  <string name="get_started">Get Started</string>
</resources>
3. SliderItemFragment

Now create a fragment for slider screen named SliderItemFragment. This slider example we are taking one fragment only, you can create separate fragment as well based on use-case.

For doing that let’s create a fragment with XML layout named is SliderItemFragment. now open the layout file paste below code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/mainContent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/ic_bg_red"
    tools:context=".SliderItemFragment"
    >

  <ImageView
      android:id="@+id/imageView"
      android:layout_width="250dp"
      android:layout_height="250dp"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      app:layout_constraintVertical_bias="0.26"
      tools:src="@tools:sample/avatars"
      />
  <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="64dp"
      android:text="Discover"
      android:textColor="@color/colorWhite"
      android:textSize="22sp"
      android:textStyle="bold"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/imageView"
      />
  <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="8dp"
      android:text="Look for things around you"
      android:textColor="@color/colorWhite"
      android:textSize="18sp"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/textView"
      />
</androidx.constraintlayout.widget.ConstraintLayout>
4. Move to MainSliderfragment

After creating the layout file let’s move to fragment java file. This class we simply binding views with java file. so let’s paste below code inside this fragment.

package com.introslider;

import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;

public class SliderItemFragment extends Fragment {

  private static final String ARG_POSITION = "slider-position";
  // prepare all title ids arrays
  @StringRes
  private static final int[] PAGE_TITLES =
      new int[] { R.string.discover, R.string.shop, R.string.offers, R.string.rewards };

  // prepare all subtitle ids arrays
  @StringRes
  private static final int[] PAGE_TEXT =
      new int[] {
          R.string.discover_text, R.string.shop_text, R.string.offers_text, R.string.rewards_text
      };
  // prepare all subtitle images arrays
  @StringRes
  private static final int[] PAGE_IMAGE =
      new int[] {
          R.drawable.ic_discover, R.drawable.ic_deals, R.drawable.ic_offers, R.drawable.ic_reward
      };

  // prepare all background images arrays
  @StringRes
  private static final int[] BG_IMAGE = new int[] {
      R.drawable.ic_bg_red, R.drawable.ic_bg_blue, R.drawable.ic_bg_green,
      R.drawable.ic_bg_purple
  };

  private int position;

  public SliderItemFragment() {
    // Required empty public constructor
  }

  /**
   * Use this factory method to create a new instance of
   *
   * @return A new instance of fragment SliderItemFragment.
   */

  public static SliderItemFragment newInstance(int position) {
    SliderItemFragment fragment = new SliderItemFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_POSITION, position);
    fragment.setArguments(args);
    return fragment;
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
      position = getArguments().getInt(ARG_POSITION);
    }
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_slider_item, container, false);
  }

  @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override
  public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    // set page background
    view.setBackground(requireActivity().getDrawable(BG_IMAGE[position]));

    TextView title = view.findViewById(R.id.textView);
    TextView titleText = view.findViewById(R.id.textView2);
    ImageView imageView = view.findViewById(R.id.imageView);

    // set page title
    title.setText(PAGE_TITLES[position]);
    // set page sub title text
    titleText.setText(PAGE_TEXT[position]);
    // set page image
    imageView.setImageResource(PAGE_IMAGE[position]);
  }
}
5. Create a subclass of FragmentPagerAdapter named is SliderPagerAdapter
package com.introslider;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

public class SliderPagerAdapter extends FragmentPagerAdapter {
  public SliderPagerAdapter(@NonNull FragmentManager fm, int behavior) {
    super(fm, behavior);
  }

  @NonNull @Override public Fragment getItem(int position) {
    return SliderItemFragment.newInstance(position);
  }
  // size is hardcoded 
  @Override public int getCount() {
    return 4;
  }
}
6. Finally, open MainActivity and paste below code

Your all resource is ready to use, let’s bind the XML layout with view using below code.

package com.introslider;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity {

  private ViewPager viewPager;
  private Button button;
  private SliderPagerAdapter adapter;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // making activity full screen
    if (Build.VERSION.SDK_INT >= 21) {
      getWindow().getDecorView()
          .setSystemUiVisibility(
              View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }
    setContentView(R.layout.activity_main);
    // hide action bar you can use NoAction theme as well
    getSupportActionBar().hide();
    // bind views
    viewPager = findViewById(R.id.pagerIntroSlider);
    TabLayout tabLayout = findViewById(R.id.tabs);
    button = findViewById(R.id.button);

    // init slider pager adapter
    adapter = new SliderPagerAdapter(getSupportFragmentManager(),
        FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);

    // set adapter
    viewPager.setAdapter(adapter);

    // set dot indicators
    tabLayout.setupWithViewPager(viewPager);

    // make status bar transparent
    changeStatusBarColor();

    button.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        if (viewPager.getCurrentItem() < adapter.getCount()) {
          viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
        }
      }
    });

    /**
     * Add a listener that will be invoked whenever the page changes
     * or is incrementally scrolled
     */
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
      @Override
      public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

      }

      @Override public void onPageSelected(int position) {
        if (position == adapter.getCount() - 1) {
          button.setText(R.string.get_started);
        } else {
          button.setText(R.string.next);
        }
      }

      @Override public void onPageScrollStateChanged(int state) {

      }
    });
  }

  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);
    }
  }
}

Conclusion

That All :). In this android app example, We have learned how to build intro slider for your app. I hope it’s helpful for you, then help me by sharing this post with all your friends who learning android app development.

Get Solution Code

If you have any queries please put your comment below.

5 Comments

  1. Frency Layal F Reply

    Where I can put the code to start my login activity by clicking “get started”?

    • if(viewPager.getCurrentItem() == adapter.getCount() ){
      startActivity()
      }

  2. Juan Billet Reply

    Hello, thank you for this example on sliders ! If i want to get swips going up and down, do i have to use MotionEvents ?
    There is one thing i didn’t get in your code, how do you make it possible to change pages by swiping ? I didn’t see anything for the swiping.

    Best regards,
    Juan.

  3. Muhammad Zawawi Bin Manja Reply

    thanks broo.. already try androidhive introslider but not work.

Write A Comment