How to create OnBoarding Screens or Slider Screens with Shared Preference in android | Todo Android app using Node JS and REST API | Part 2
Today we’ll create OnBoarding screens in android using shared preference. OnBoarding screens are used as introduction screens. It gives us a clear view of the app. It is not necessary to always use the onboarding screens, it depends on the UI/UX of the app.
But here we have created an onboarding screen with shared preference so that everyone gets an idea of how to create slider screens in android.
Go through the previous part of this project otherwise, you will not understand the links between the activities. CLICK HERE for Part 1.
Before going to create, first, let’s see what shared preference is.
Shared Preference
Shared preferences allow you to store small amounts of primitive data as key/value pairs in a file on the device. To get a handle on a preference file, and to read, write, and manage preference data, use the SharedPreferences class. The Android framework manages the shared preferences file itself
Here we use shared preference on these onboarding screens because when an existing user opens the app he/she will not encounter the onboarding screens every time. But when a new user opens the app he/she will encounter the onboarding screens once. So to store that data we used shared preference.
Now let’s see how to create these onboarding screens and store that data using shared preference.
Overview
Part 1: create the Viewpager
- Create a new activity for the onboarding screens (/package/new/activity/OnboardingActivity). In the XML file create a view pager for the slider screens. Below the view pager, we are going to add some buttons. The below image will give you a clear idea.
- In activity_onboarding.xml file
<?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”
android:background=”@drawable/on_page”
tools:context=”.OnboardingActivity”
android:padding=”20dp”><androidx.viewpager.widget.ViewPager
android:id=”@+id/slider”
android:layout_width=”match_parent”
android:layout_height=”0dp”
app:layout_constraintBottom_toTopOf=”@+id/relativeLayout”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent”></androidx.viewpager.widget.ViewPager>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/skip_btn”
android:text=”@string/skip”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
android:background=”#00000000"
android:textColor=”@color/white”
android:onClick=”skip”
android:fontFamily=”@font/poppins” /><RelativeLayout
android:id=”@+id/relativeLayout”
android:layout_width=”match_parent”
android:layout_height=”120dp”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintStart_toStartOf=”parent”><Button
android:id=”@+id/get_started_btn”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginStart=”25dp”
android:layout_marginEnd=”25dp”
android:background=”@drawable/button_back”
android:fontFamily=”@font/poppins_semibold”
android:text=”Get Started”
android:textColor=”@color/colorAccent”
android:textSize=”19sp”
android:textAllCaps=”false”
android:onClick=”getStarted”
android:visibility=”invisible”/><LinearLayout
android:id=”@+id/dots”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentBottom=”true”
android:layout_alignParentStart=”true”
android:orientation=”horizontal”/><Button
android:id=”@+id/next_btn”
android:layout_width=”wrap_content”
android:layout_height=”40dp”
android:layout_alignParentRight=”true”
android:layout_alignParentBottom=”true”
android:background=”@drawable/button_back”
android:fontFamily=”@font/poppins_semibold”
android:text=”Next”
android:textSize=”16sp”
android:onClick=”next”
android:textAllCaps=”false”
android:textColor=”@color/colorAccent” />
</RelativeLayout></androidx.constraintlayout.widget.ConstraintLayout>
- As you see here we add a view pager, one button for Skip the screens, one button for Next to go to the next screen, one button for go to the main screen which is the Get Started button, and a Linear Layout for the dots. We will create the dots using HTML codes.
Part 2: create the items
- Whatever we want to display in the view pager we need to create those items. The below image will give you an idea.
- For the items create a new layout file (/res/layout/slides_layot.xml) under the res folder.
<?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”><ImageView
android:id=”@+id/slider_image”
android:layout_width=”230dp”
android:layout_height=”280dp”
android:layout_marginTop=”50dp”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintHorizontal_bias=”0.5"
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:srcCompat=”@drawable/onb4" /><TextView
android:id=”@+id/slider_header”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:fontFamily=”@font/poppins_bold”
android:text=”@string/onboarding_title1"
android:textSize=”23sp”
android:gravity=”center”
android:textColor=”@color/colorAccent”
android:textAlignment=”center”
android:includeFontPadding=”false”
android:layout_marginTop=”15dp”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintHorizontal_bias=”0.497"
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toBottomOf=”@+id/slider_image” /><TextView
android:id=”@+id/slider_desc”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:textAlignment=”center”
android:fontFamily=”@font/poppins”
android:textSize=”14sp”
android:gravity=”center”
android:layout_marginTop=”20dp”
android:textColor=”@color/colorAccent”
android:text=”@string/onboarding_des1"
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toBottomOf=”@+id/slider_header” />
</androidx.constraintlayout.widget.ConstraintLayout>
You can design it as per your requirements. I just give you an idea.
Part 3: create an adapter class
Now create an adapter class (/package/adapter/SliderAdapter.java) to hold the slider layout. Here we inflate the slides_layout.xml file that we created in the previous step and import out data.
package com.codewithgolap.snapshot.helper;
import android.content.Context;
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.constraintlayout.widget.ConstraintLayout;
import androidx.viewpager.widget.PagerAdapter;import com.codewithgolap.snapshot.R;
public class SliderAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;public SliderAdapter(Context context) {
this.context = context;
}int images[] = {
R.drawable.onb1, R.drawable.onb2, R.drawable.onb3, R.drawable.onb4
};
int headings[] = {
R.string.onboarding_title1, R.string.onboarding_title2, R.string.onboarding_title3, R.string.onboarding_title3
};
int descriptions[] = {
R.string.onboarding_des1,
R.string.onboarding_des2,
R.string.onboarding_des3,
R.string.onboarding_des3
};@Override
public int getCount() {
return headings.length;
}@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == (ConstraintLayout) object;
}@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slides_layout,container, false);ImageView imageView = view.findViewById(R.id.slider_image);
TextView heading = view.findViewById(R.id.slider_header);
TextView desc = view.findViewById(R.id.slider_desc);imageView.setImageResource(images[position]);
heading.setText(headings[position]);
desc.setText(descriptions[position]);container.addView(view);
return view;
}@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((ConstraintLayout) object);
}
}
Part 4: add the functionality
- Now in the onboarding java file, we add our functionalities for the buttons, view pager and also create our dots
- First, create hooks.
public class OnboardingActivity extends AppCompatActivity {
ViewPager viewPager;
LinearLayout dotsLayout;
SliderAdapter sliderAdapter;
TextView[] dots;
Button letsGetStarted, nextbtn;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onboarding);viewPager = findViewById(R.id.slider);
dotsLayout = findViewById(R.id.dots);
letsGetStarted = findViewById(R.id.get_started_btn);
nextbtn = findViewById(R.id.next_btn);}
}
- Second, call the adapter and set the adapter with our view pager.
public class OnboardingActivity extends AppCompatActivity {
ViewPager viewPager;
LinearLayout dotsLayout;
SliderAdapter sliderAdapter;
TextView[] dots;
Button letsGetStarted, nextbtn;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onboarding);viewPager = findViewById(R.id.slider);
dotsLayout = findViewById(R.id.dots);
letsGetStarted = findViewById(R.id.get_started_btn);
nextbtn = findViewById(R.id.next_btn);//call adapter
sliderAdapter = new SliderAdapter(this);
viewPager.setAdapter(sliderAdapter);}
}
- Third, create the dots
public class OnboardingActivity extends AppCompatActivity {
ViewPager viewPager;
LinearLayout dotsLayout;
SliderAdapter sliderAdapter;
TextView[] dots;
Button letsGetStarted, nextbtn;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onboarding);viewPager = findViewById(R.id.slider);
dotsLayout = findViewById(R.id.dots);
letsGetStarted = findViewById(R.id.get_started_btn);
nextbtn = findViewById(R.id.next_btn);//call adapter
sliderAdapter = new SliderAdapter(this);
viewPager.setAdapter(sliderAdapter);addDots(0);
}
private void addDots(int position) {
dots = new TextView[4];
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml(“•”));
dots[i].setTextSize(30);
dots[i].setTextColor(getResources().getColor(R.color.dotsColor));dotsLayout.addView(dots[i]);
}if (dots.length > 0) {
dots[position].setTextColor(getResources().getColor(R.color.buttonColor));
}
}
}
- Fourth, add on page listener (addOnPageListener) on the view pager to swipe left and right. And to hold the current position of the page create a global variable for the position.
public class OnboardingActivity extends AppCompatActivity {
ViewPager viewPager;
LinearLayout dotsLayout;
SliderAdapter sliderAdapter;
TextView[] dots;
Button letsGetStarted, nextbtn;
Animation animation;
int currentPosition;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onboarding);viewPager = findViewById(R.id.slider);
dotsLayout = findViewById(R.id.dots);
letsGetStarted = findViewById(R.id.get_started_btn);
nextbtn = findViewById(R.id.next_btn);//call adapter
sliderAdapter = new SliderAdapter(this);
viewPager.setAdapter(sliderAdapter);addDots(0);
viewPager.addOnPageChangeListener(changeListener);}
private void addDots(int position) {
dots = new TextView[4];
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml(“•”));
dots[i].setTextSize(30);
dots[i].setTextColor(getResources().getColor(R.color.dotsColor));dotsLayout.addView(dots[i]);
}if (dots.length > 0) {
dots[position].setTextColor(getResources().getColor(R.color.buttonColor));
}
}ViewPager.OnPageChangeListener changeListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
@Override
public void onPageSelected(int position) {
addDots(position);currentPosition = position;
if (position == 0) {
nextbtn.setVisibility(View.VISIBLE);
letsGetStarted.setVisibility(View.INVISIBLE);
} else if (position == 1) {
nextbtn.setVisibility(View.VISIBLE);
letsGetStarted.setVisibility(View.INVISIBLE);
} else if (position == 2) {
nextbtn.setVisibility(View.VISIBLE);
letsGetStarted.setVisibility(View.INVISIBLE);
} else {
animation = AnimationUtils.loadAnimation(OnboardingActivity.this, R.anim.bottom_anim);
letsGetStarted.setAnimation(animation);
letsGetStarted.setVisibility(View.VISIBLE);
nextbtn.setVisibility(View.INVISIBLE);
}}
@Override
public void onPageScrollStateChanged(int state) {}
};
}
Here I add a bottom animation in the Get Started button to looks better. If you want you can use it or leave it.
- Last, add on click listener on the buttons.
public class OnboardingActivity extends AppCompatActivity {
ViewPager viewPager; LinearLayout dotsLayout; SliderAdapter sliderAdapter; TextView[] dots; Button letsGetStarted, nextbtn; Animation animation; int currentPosition;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_onboarding);
viewPager = findViewById(R.id.slider); dotsLayout = findViewById(R.id.dots); letsGetStarted = findViewById(R.id.get_started_btn); nextbtn = findViewById(R.id.next_btn);
//call adapter sliderAdapter = new SliderAdapter(this); viewPager.setAdapter(sliderAdapter);
addDots(0); viewPager.addOnPageChangeListener(changeListener);
}
public void getStarted(View view){ startActivity(new Intent(this, ExtraActivity.class)); finish(); }
public void skip(View view){ startActivity(new Intent(this, ExtraActivity.class)); finish(); }
public void next(View view){ viewPager.setCurrentItem(currentPosition + 1); }
private void addDots(int position) { dots = new TextView[4]; dotsLayout.removeAllViews(); for (int i = 0; i < dots.length; i++) { dots[i] = new TextView(this); dots[i].setText(Html.fromHtml(“•”)); dots[i].setTextSize(30); dots[i].setTextColor(getResources().getColor(R.color.dotsColor)); dotsLayout.addView(dots[i]); }
if (dots.length > 0) { dots[position].setTextColor(getResources().getColor(R.color.buttonColor)); } }
ViewPager.OnPageChangeListener changeListener = new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
@Override public void onPageSelected(int position) { addDots(position); currentPosition = position;
if (position == 0) { nextbtn.setVisibility(View.VISIBLE); letsGetStarted.setVisibility(View.INVISIBLE); } else if (position == 1) { nextbtn.setVisibility(View.VISIBLE); letsGetStarted.setVisibility(View.INVISIBLE); } else if (position == 2) { nextbtn.setVisibility(View.VISIBLE); letsGetStarted.setVisibility(View.INVISIBLE); } else { animation = AnimationUtils.loadAnimation(OnboardingActivity.this, R.anim.bottom_anim); letsGetStarted.setAnimation(animation); letsGetStarted.setVisibility(View.VISIBLE); nextbtn.setVisibility(View.INVISIBLE); }
}
@Override public void onPageScrollStateChanged(int state) { } }; }
Part 5: shared preference
Now to handle the shared preference go to the Splash screen that we created in the last tutorial (CLICK HERE if you’re new) and define the shared preference and handle it into the postDeayed function.
public class SplashActivity extends AppCompatActivity { ……
SharedPreferences onBoardingScreen;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
………
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
onBoardingScreen = getSharedPreferences(“onBoardingScreen”, MODE_PRIVATE);
boolean isFirstTime = onBoardingScreen.getBoolean(“firstTime”, true);
if (isFirstTime){
SharedPreferences.Editor editor = onBoardingScreen.edit();
editor.putBoolean(“firstTime”, false);
editor.commit();
startActivity(new Intent(SplashActivity.this, OnboardingActivity.class));
finish();
}
else {
startActivity(new Intent(SplashActivity.this, ExtraActivity.class));
finish();
}
}
}, 3500);
}
}
as you see if the user is a first-time visit the app then he/she directly goes to the Onboarding activity and if the user is not the first timer then he/she redirected to the Login activity that we will see in the next tutorial.
In the next part, we will design our Register and Login screens.