Thursday, December 26, 2024
Google search engine
HomeLanguagesJavaHow to Create WhatsApp Stories View in Android?

How to Create WhatsApp Stories View in Android?

Stories are now becoming one of the most seen features in many different apps such as WhatsApp, LinkedIn, Instagram, and many more. In this article, we will take a look at creating a similar type of view in our Android App. 

What we are going to build in this article? 

We will be building a simple application in which we will be creating a stories view which we can get to see on WhatsApp. We will be adding some fixed images to it. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add dependency and JitPack Repository

Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.   

implementation ‘com.github.shts:StoriesProgressView:3.0.0’

Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section.

allprojects {

 repositories {

   …

   maven { url “https://jitpack.io” }

     }

}

After adding this dependency sync your project and now we will move towards its implementation.  

Step 3: Updating the theme to NoActionBar in the themes.xml file

Navigate to app > res > values > themes.xml and inside that change the base application theme to NoActionBar. You can get to see the code for the themes.xml file below. 

XML




<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.GFGParse" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!--below is the text color-->
        <item name="android:textColor">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>
</resources>


Step 4: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/idRLBack"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--button for opening our stories activity-->
    <Button
        android:id="@+id/idBtnStories"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:onClick="ShowStories"
        android:text="Show Stories" />
 
</RelativeLayout>


Step 5: Creating a new activity for displaying stories 

Navigate to the app > java > your app’s package name > Right-click on it > New > Activity and select as Empty Activity and name it as StoriesActivity and create a new activity. 

Step 6: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.content.Intent;
import android.os.Bundle;
import android.view.View;
 
import androidx.appcompat.app.AppCompatActivity;
 
public class MainActivity extends AppCompatActivity {
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    public void ShowStories(View view) {
        // on below line we are opening a new activity using intent.
        Intent i = new Intent(MainActivity.this, StoriesActivity.class);
        startActivity(i);
    }
}


Step 7: Working with the activity_stories.xml file

Navigate to the app > res > layout > activity_stories.xml and add the below code to that file. Below is the code for the activity_stories.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<!--we are using merge as a parent layout for merging all our views-->
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".StoriesActivity">
 
    <!--below is the image view where we will
        be displaying images in our stories-->
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/purple_200"
        android:contentDescription="@null"
        tools:src="@drawable/logo1" />
 
    <!--on below line we are creating
        linear layout for our views-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
         
        <!--view to handle move to previous image-->
        <View
            android:id="@+id/reverse"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />
         
        <!--view to move to the next image-->
        <View
            android:id="@+id/skip"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />
         
    </LinearLayout>
 
    <!--below widget is use to create indicator for our stories at top-->
    <jp.shts.android.storiesprogressview.StoriesProgressView
        android:id="@+id/stories"
        android:layout_width="match_parent"
        android:layout_height="3dp"
        android:layout_gravity="top"
        android:layout_marginTop="8dp"
        android:paddingLeft="8dp"
        android:paddingRight="8dp" />
 
</merge>


Step 8: Working with the StoriesActivity.java file

Go to the StoriesActivity.java file and refer to the following code. Below is the code for the StoriesActivity.java file. Comments are added inside the code to understand the code in more detail.

Note: Images are added in the drawable folder. 

Java




import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
 
import androidx.appcompat.app.AppCompatActivity;
 
import jp.shts.android.storiesprogressview.StoriesProgressView;
 
public class StoriesActivity extends AppCompatActivity implements StoriesProgressView.StoriesListener {
 
    // on below line we are creating a int array
    // in which we are storing all our image ids.
    private final int[] resources = new int[]{
            R.drawable.logo1,
            R.drawable.logo2,
            R.drawable.logo1,
            R.drawable.logo2,
            R.drawable.logo1,
            R.drawable.logo2,
    };
 
    // on below line we are creating variable for
    // our press time and time limit to display a story.
    long pressTime = 0L;
    long limit = 500L;
 
    // on below line we are creating variables for
    // our progress bar view and image view .
    private StoriesProgressView storiesProgressView;
    private ImageView image;
 
    // on below line we are creating a counter
    // for keeping count of our stories.
    private int counter = 0;
 
    // on below line we are creating a new method for adding touch listener
    private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // inside on touch method we are
            // getting action on below line.
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
 
                    // on action down when we press our screen
                    // the story will pause for specific time.
                    pressTime = System.currentTimeMillis();
 
                    // on below line we are pausing our indicator.
                    storiesProgressView.pause();
                    return false;
                case MotionEvent.ACTION_UP:
 
                    // in action up case when user do not touches
                    // screen this method will skip to next image.
                    long now = System.currentTimeMillis();
 
                    // on below line we are resuming our progress bar for status.
                    storiesProgressView.resume();
 
                    // on below line we are returning if the limit < now - presstime
                    return limit < now - pressTime;
            }
            return false;
        }
    };
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         
        // inside in create method below line is use to make a full screen.
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_stories);
         
        // on below line we are initializing our variables.
        storiesProgressView = (StoriesProgressView) findViewById(R.id.stories);
         
        // on below line we are setting the total count for our stories.
        storiesProgressView.setStoriesCount(resources.length);
         
        // on below line we are setting story duration for each story.
        storiesProgressView.setStoryDuration(3000L);
         
        // on below line we are calling a method for set
        // on story listener and passing context to it.
        storiesProgressView.setStoriesListener(this);
         
        // below line is use to start stories progress bar.
        storiesProgressView.startStories(counter);
         
        // initializing our image view.
        image = (ImageView) findViewById(R.id.image);
         
        // on below line we are setting image to our image view.
        image.setImageResource(resources[counter]);
         
        // below is the view for going to the previous story.
        // initializing our previous view.
        View reverse = findViewById(R.id.reverse);
         
        // adding on click listener for our reverse view.
        reverse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // inside on click we are
                // reversing our progress view.
                storiesProgressView.reverse();
            }
        });
         
        // on below line we are calling a set on touch
        // listener method to move towards previous image.
        reverse.setOnTouchListener(onTouchListener);
 
        // on below line we are initializing
        // view to skip a specific story.
        View skip = findViewById(R.id.skip);
        skip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // inside on click we are
                // skipping the story progress view.
                storiesProgressView.skip();
            }
        });
        // on below line we are calling a set on touch
        // listener method to move to next story.
        skip.setOnTouchListener(onTouchListener);
    }
 
    @Override
    public void onNext() {
        // this method is called when we move
        // to next progress view of story.
        image.setImageResource(resources[++counter]);
    }
 
    @Override
    public void onPrev() {
         
        // this method is called when we move to previous story.
        // on below line we are decreasing our counter
        if ((counter - 1) < 0) return;
         
        // on below line we are setting image to image view
        image.setImageResource(resources[--counter]);
    }
 
    @Override
    public void onComplete() {
        // when the stories are completed this method is called.
        // in this method we are moving back to initial main activity.
        Intent i = new Intent(StoriesActivity.this, MainActivity.class);
        startActivity(i);
        finish();
    }
 
    @Override
    protected void onDestroy() {
        // in on destroy method we are destroying
        // our stories progress view.
        storiesProgressView.destroy();
        super.onDestroy();
    }
}


Now run your app and see the output of the app. 

Output: 

RELATED ARTICLES

Most Popular

Recent Comments