Author

vishal swami

Browsing

Android studio Xml, Kotlin payment app ui with complete source code for free by Shashank Singhal. Ideal for payment app, homepage design templates etc.

Author

Author Name:- Vishal Swami
GitHub Link:- https://github.com/

Here’s an example of a payment app UI design using Android Studio. Below is a step-by-step guide:

Step 1: Set up your project
Create a new Android project in Android Studio.

Step 2: Create the layout files
Create the following layout files in your project:

activity_payment.xml:

<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"
    tools:context=".PaymentActivity">

    <!-- Payment amount -->
    <TextView
        android:id="@+id/textViewAmount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="Enter payment amount"
        android:textSize="18sp" />

    <!-- Payment input field -->
    <EditText
        android:id="@+id/editTextPayment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="32dp"
        android:hint="Payment amount"
        android:inputType="numberDecimal"
        android:textSize="24sp" />

    <!-- Payment methods -->
    <TextView
        android:id="@+id/textViewPaymentMethods"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="Select payment method"
        android:textSize="18sp" />

    <!-- Payment method options -->
    <RadioGroup
        android:id="@+id/radioGroupPaymentMethods"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="32dp"
        android:orientation="vertical">

        <RadioButton
            android:id="@+id/radioButtonCreditCard"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Credit Card" />

        <RadioButton
            android:id="@+id/radioButtonPayPal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="PayPal" />

        <RadioButton
            android:id="@+id/radioButtonGooglePay"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Google Pay" />
    </RadioGroup>

    <!-- Pay button -->
    <Button
        android:id="@+id/buttonPay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="32dp"
        android:text="Pay Now" />

</LinearLayout>

Step 3: Create the Activity class
Create a new Java or Kotlin class named PaymentActivity and update it with the following code:

PaymentActivity.java:

public class PaymentActivity extends AppCompatActivity {

    private TextView textViewAmount;
    private EditText editTextPayment;
    private RadioGroup radioGroupPaymentMethods;
    private Button buttonPay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment);

        textViewAmount = findViewById(R.id.textViewAmount);
        editTextPayment = findViewById(R.id.editTextPayment);
        radioGroupPaymentMethods = findViewById(R.id.radioGroupPaymentMethods);
        buttonPay = findViewById(R.id.buttonPay);

        buttonPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String paymentAmount = editTextPayment.getText().toString();
                int selectedPaymentMethodId = radioGroupPaymentMethods.getCheckedRadioButtonId();
                String paymentMethod = "";

                switch (selectedPaymentMethodId) {
                    case R.id.radioButtonCreditCard:
                        paymentMethod = "Credit Card";
                        break;
                    case R.id.radioButtonPayPal:
                        paymentMethod = "PayPal";
                        break;
                    case R.id.radioButtonGooglePay:
                        paymentMethod = "Google Pay";
                        break;
                }

                String paymentDetails = "Payment Amount: " + paymentAmount +
                        "\nPayment Method: " + paymentMethod;

                Toast.makeText(PaymentActivity.this, paymentDetails, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Step 4: Connect the Activity to the layout file
Open the AndroidManifest.xml file and add the following line inside the <application> tag:

<activity android:name=".PaymentActivity" />

Step 5: Build and run the app
Build and run your app on an emulator or physical device.

Congratulations! You have created a payment app UI design in Android Studio. The UI includes an input field for the payment amount, radio buttons for selecting the payment method, and a button to initiate the payment. When the user clicks the “Pay Now” button, a Toast message is displayed showing the payment amount and selected payment method.

Feel free to customize the UI elements and add additional functionality as per your requirements.

I’ll provide you with a sample code and explanation for creating a profile screen with a RecyclerView using Android DataBinding. Here’s a step-by-step guide:

Step 1: Set up your project
Create a new Android project in Android Studio. Make sure you have the necessary dependencies in your build.gradle file:

android {
    // ...
    dataBinding {
        enabled = true
    }
}

Step 2: Create the layout files
Create the following layout files in your project:

activity_profile.xml:

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="viewModel"
            type="com.example.yourapp.ProfileViewModel" />
    </data>

    <!-- Your profile screen layout here -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:items="@{viewModel.blogItems}"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:itemLayout="@layout/item_blog" />
    </LinearLayout>
</layout>

item_blog.xml:

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="blog"
            type="com.example.yourapp.BlogItem" />
    </data>

    <!-- Your blog item layout here -->
</layout>

Step 3: Create the ViewModel and BlogItem classes
Create the following classes in your project:

ProfileViewModel.kt:

class ProfileViewModel : ViewModel() {
    val blogItems: LiveData<List<BlogItem>> = MutableLiveData(
        listOf(
            BlogItem("Title 1", "Content 1"),
            BlogItem("Title 2", "Content 2"),
            BlogItem("Title 3", "Content 3")
        )
    )
}

class BlogItem(val title: String, val content: String)

Step 4: Create the Adapter and ViewHolder
Create the following classes in your project:

BlogAdapter.kt:

class BlogAdapter(private val blogItems: List<BlogItem>) :
    RecyclerView.Adapter<BlogAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val binding: ItemBlogBinding = DataBindingUtil.inflate(
            inflater, R.layout.item_blog, parent, false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(blogItems[position])
    }

    override fun getItemCount(): Int = blogItems.size

    class ViewHolder(private val binding: ItemBlogBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(blogItem: BlogItem) {
            binding.blog = blogItem
            binding.executePendingBindings()
        }
    }
}

Step 5: Connect everything in your Activity or Fragment
Update your ProfileActivity or ProfileFragment to include the following code:

ProfileActivity.kt:

class ProfileActivity : AppCompatActivity() {

    private lateinit var binding: ActivityProfileBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_profile)

        val viewModel = ViewModelProvider(this).get(ProfileViewModel::class.java)
        binding.viewModel = viewModel

        val adapter = BlogAdapter(viewModel.blogItems.value ?: emptyList())
        binding.recyclerView.adapter = adapter
    }
}

That’s it! You have now created a profile screen with a RecyclerView using Android DataBinding. Make sure to replace com.example.yourapp it with the appropriate package name in the code.

Remember to customize the layout files and the BlogItem class according to your requirements. You can also update the blog items dynamically by modifying the blogItems LiveData in the ViewModel.

Hope this helps you get started with your profile screen implementation!

Here’s an example of an Android application that allows users to choose an image from the camera or gallery and perform cropping functionality using the “Android Image Cropper” library.

Step 1: Set up the project

Start by creating a new Android project in Android Studio. Make sure you have the necessary dependencies and permissions in your project’s build.gradle file:

dependencies {
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.+'
}

Also, make sure you have the necessary permissions in your AndroidManifest.xml file:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

Step 2: Create the layout

Create a layout file called activity_main.xml with the following code:

<RelativeLayout 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:paddingLeft="16dp"
    android:paddingTop="16dp"
    android:paddingRight="16dp"
    android:paddingBottom="16dp"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:scaleType="centerInside"
        android:src="@drawable/placeholder" />

    <Button
        android:id="@+id/btnChooseImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/imageView"
        android:text="Choose Image" />

    <Button
        android:id="@+id/btnCropImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnChooseImage"
        android:text="Crop Image"
        android:enabled="false" />

</RelativeLayout>

Step 3: Implement the functionality in the MainActivity

Open MainActivity.java and add the following code:

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CAMERA_PERMISSION = 200;
    private static final int REQUEST_IMAGE_CAPTURE = 100;
    private static final int REQUEST_IMAGE_GALLERY = 101;

    private ImageView imageView;
    private Button btnChooseImage;
    private Button btnCropImage;

    private Uri imageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.imageView);
        btnChooseImage = findViewById(R.id.btnChooseImage);
        btnCropImage = findViewById(R.id.btnCropImage);

        btnChooseImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseImage();
            }
        });

        btnCropImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cropImage(imageUri);
            }
        });
    }

    private void chooseImage() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
        } else {
            openImageChooser();
        }
    }

    private void openImageChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_IMAGE_GALLERY);
    }

    private void cropImage(Uri imageUri) {
        CropImage.activity(imageUri)
                .setGuidelines(CropImageView.Guidelines.ON)
                .setAspectRatio(1, 1)
                .start(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            cropImage(imageUri);
        } else if (requestCode == REQUEST_IMAGE_GALLERY && resultCode == RESULT_OK && data != null) {
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
                imageView.setImageBitmap(bitmap);
                imageUri = data.getData();
                btnCropImage.setEnabled(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                Uri resultUri = result.getUri();
                try {
                    Bitmap croppedBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), resultUri);
                    imageView.setImageBitmap(croppedBitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
                error.printStackTrace();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CAMERA_PERMISSION && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            openImageChooser();
        }
    }
}

That’s it! Now you have an Android application that allows users to choose an image from the camera or gallery and perform cropping functionality. Remember to replace the placeholder image with an actual placeholder image of your choice.

Note: Don’t forget to add the necessary runtime permissions check in your code to handle permissions for accessing the camera and gallery.

Step 1: Sign up for a Paytm merchant account
To integrate the PayTM payment gateway, you need to sign up for a PayTM merchant account. Visit the PayTM Developer Portal (https://developer.paytm.com/) and follow the registration process to create your merchant account.

Step 2: Set up PayTM SDK in your project

  1. Open your Android project in Android Studio.
  2. Add the following dependency to your app-level build. gradle file:
implementation 'com.paytm:pgplussdk:1.4.3'
  1. Sync your project to download the PayTM SDK.

Step 3: Obtain merchant credentials
After signing up for a merchant account, you will receive the necessary credentials from PayTM. These include the merchant ID and merchant key, which you’ll need for integration.

Step 4: Create a PayTM activity
Create a new activity in your Android project to handle the PayTM payment process. For example, create a PaytmActivity.java file.

Step 5: Implement the PayTM payment process
In the PaytmActivity.java file, implement the following steps:

  1. Initialize the PayTM service in the onCreate() method:
PaytmPGService service = PaytmPGService.getStagingService(); // or PaytmPGService.getProductionService() for production environment
  1. Set up the payment parameters and listener:
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put("MID", "YOUR_MERCHANT_ID");
paramMap.put("ORDER_ID", "UNIQUE_ORDER_ID");
paramMap.put("CUST_ID", "CUSTOMER_ID");
paramMap.put("CHANNEL_ID", "WAP");
paramMap.put("TXN_AMOUNT", "AMOUNT");
paramMap.put("WEBSITE", "WEBSTAGING"); // for staging environment, use "DEFAULT" for production
paramMap.put("INDUSTRY_TYPE_ID", "Retail");
paramMap.put("CALLBACK_URL", "CALLBACK_URL"); // the URL to which PayTM will send the payment response

PaytmOrder order = new PaytmOrder(paramMap);

service.initialize(order, null);

Replace the placeholders with the appropriate values from your merchant account.

  1. Start the payment transaction:
service.startPaymentTransaction(this, true, true, new PaytmPaymentTransactionCallback() {
    @Override
    public void onTransactionResponse(Bundle inResponse) {
        // Handle the payment response
    }

    @Override
    public void networkNotAvailable() {
        // Handle network error
    }

    @Override
    public void clientAuthenticationFailed(String inErrorMessage) {
        // Handle authentication error
    }

    @Override
    public void someUIErrorOccurred(String inErrorMessage) {
        // Handle UI error
    }

    @Override
    public void onErrorLoadingWebPage(int iniErrorCode, String inErrorMessage, String inFailingUrl) {
        // Handle web page loading error
    }

    @Override
    public void onBackPressedCancelTransaction() {
        // Handle transaction cancellation
    }

    @Override
    public void onTransactionCancel(String inErrorMessage, Bundle inResponse) {
        // Handle transaction cancellation
    }
});
  1. Handle the payment response in the onTransactionResponse() method:
@Override
public void onTransactionResponse(Bundle inResponse) {
    String status = inResponse.getString("STATUS");
    String message = inResponse.getString("RESPMSG");

    if (status != null && status.equals("TXN_SUCCESS")) {
        // Payment was successful
    } else {
        // Payment failed
    }
}

Step 6: Connect the PayTM activity to your app
Finally, you need to connect the PayTM activity to your e-commerce app. For example, you can add a button to the shopping cart screen and launch the PayTM activity when the user selects the payment option.

That’s it! You have now integrated the PayTM payment gateway into your Android e-commerce app. Remember to replace the placeholder values with your actual merchant credentials and customize the code according to your app’s requirements.

Please note that this guide provides a basic integration example. For a complete and detailed implementation, including error handling and additional features, you may need to refer to the official PayTM documentation or consult their support resources.

Slide transition between screens is common in Android applications. We can use the navigation components or a swipe-able view to create this transition. A common swipe-able view is ViewPager2. The ViewPager library has been around for quite a while.

Introduction

This view allows the developer to display views or fragments to the user in a swipe-able format. This feature is common in content display applications and in app setups.

ViewPager2 is often integrated with TabLayout. A TabLayout indicates the current page and allows a user to switch through pages.

Prerequisites

To follow through with this tutorial, you will need to:

  1. Have Android Studio installed.
  2. Have a basic knowledge of building Android applications.
  3. Have a basic understanding of Kotlin programming language.

Let’s get started!

  1. First, let’s set up the necessary dependencies in your app-level build.gradle file:
implementation 'androidx.viewpager2:viewpager2:1.0.0'
implementation 'com.google.android.material:material:1.4.0'
  1. Next, create a new layout file for your main activity (activity_main.xml). The layout will contain a TabLayout and a ViewPager2:
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            app:tabTextColor="@color/tab_text_color"
            app:tabSelectedTextColor="@color/tab_selected_text_color"
            app:tabIndicatorColor="@color/tab_indicator_color" />

    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
  1. Create a new layout file for each of your blog fragments (fragment_blog.xml). Customize it to your needs:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- Add your blog content views here -->

</LinearLayout>
  1. Create a new class for your ViewPager adapter (BlogPagerAdapter.java):
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import java.util.List;

public class BlogPagerAdapter extends FragmentStateAdapter {
    private List<Fragment> fragments;

    public BlogPagerAdapter(@NonNull FragmentActivity fragmentActivity, List<Fragment> fragments) {
        super(fragmentActivity);
        this.fragments = fragments;
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return fragments.get(position);
    }

    @Override
    public int getItemCount() {
        return fragments.size();
    }
}
  1. Finally, in your MainActivity, set up the TabLayout and ViewPager2:
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ViewPager2 viewPager;
    private TabLayout tabLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new BlogFragment1());
        fragments.add(new BlogFragment2());
        fragments.add(new BlogFragment3());

        BlogPagerAdapter adapter = new BlogPagerAdapter(this, fragments);
        viewPager.setAdapter(adapter);

        new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
            // Customize the tab names as per your requirement
            switch (position) {
                case 0:
                    tab.setText("Blog 1");
                    break;
                case 1:
                    tab.setText("Blog 2");
                    break;
                case 2:
                    tab.setText("Blog 3");
                    break;
            }
        }).attach();
    }
}

That’s it! You can now create separate fragments (BlogFragment1, BlogFragment2, etc.) and customize them for each blog page.

Note: Make sure to replace the colors and other resources with your own preferences in the XML files. Also, remember to register the MainActivity in your AndroidManifest.xml file.

This is a basic example to get you started. You can further enhance it with additional features and customization based on your requirements.

Pinterest UI clone by Shashank Singhal. Ideal template for listing, social media, and single-page applications.

https://github.com/vishaldroidx/-PinterestAppUI-Android

Credits:

 © All contents from GitHub
AuthorVishal Swami

If you like this post, please leave your suggestions and comments below 

Did you know? 
your comments can motivate us to create wonders.

Android studio XML, Kotlin payment app ui with complete source code for free by Vishal Swami. Ideal for payment apps, homepage design templates etc.


GitHub Link:- https://github.com/vishaldroidx/PaymentAppUI-Android

Credits:

 © All contents from GitHub
AuthorVishal Swami

If you like this post, please leave your suggestions and comments below 

Did you know? 
your comments can motivate us to create wonders.

Classroom UI Android studio project by Shashank Singhal. Ideal template for edutech, e-commerce, listing, and social media applications.

Author

Author Name:- Vishal Swami
GitHub Link:- https://github.com/vishaldroidx

Credits:

 © All contents from GitHub
AuthorVishal Swami

If you like this post, please leave your suggestions and comments below 

Did you know? 
your comments can motivate us to create wonders.

We all know that Android Marshmallow introduced runtime permissions letting user to allow or deny any permission at runtime. Implementing runtime permissions is a tedious process and developer needs to write lot of code just to get a single permission.

In this article, we are going to simplify the process of adding the runtime permissions using Dexter library. Using this library, the permissions can be implemented in few minutes.

This is an introductory article about the Dexter covering basic features offered by the library. Dexter provides other features like using it with SnackBar, different types of listeners, error handling and few other. You can find more information on Dexter’s developer page.

1. Dexter Permissions Library

To get started with Dexter, add the dependency in your build.gradle

dependencies {
    // Dexter runtime permissions
    implementation 'com.karumi:dexter:4.2.0'
}

1.1 Requesting Single Permission

To request a single permission, you can use withPermission() method by passing the required permission. You also need a PermissionListener callback to receive the state of the permission.

> onPermissionGranted() will be called once the permission is granted.

> onPermissionDenied() will be called when the permission is denied. Here you can check whether the permission is permanently denied by using response.isPermanentlyDenied() condition.

The below code requests CAMERA permission.

Dexter.withActivity(this)
                .withPermission(Manifest.permission.CAMERA)
                .withListener(new PermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse response) {
                        // permission is granted, open the camera
                    }
 
                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse response) {
                        // check for permanent denial of permission
                        if (response.isPermanentlyDenied()) {
                            // navigate user to app settings
                        }
                    }
 
                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).check();

1.2 Requesting Multiple Permissions

To request multiple permissions at the same time, you can use withPermissions() method. Below code requests STORAGE and LOCATION permissions.

Dexter.withActivity(this)
                .withPermissions(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {
                        // check if all permissions are granted
                        if (report.areAllPermissionsGranted()) {
                            // do you work now
                        }
 
                        // check for permanent denial of any permission
                        if (report.isAnyPermissionPermanentlyDenied()) {
                            // permission is denied permenantly, navigate user to app settings
                        }
                    }
 
                    @Override
                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                })
                .onSameThread()
                .check();

1.3 Error Handling

You can also catch any errors occurred while integrating the library using PermissionRequestErrorListener.

Dexter.withActivity(this)
                .withPermissions(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .withListener(listener)
                .withErrorListener(new PermissionRequestErrorListener() {
                    @Override
                    public void onError(DexterError error) {
                        Toast.makeText(getApplicationContext(), "Error occurred! " + error.toString(), Toast.LENGTH_SHORT).show();
                    }
                })
                .check();

Now let’s see how to use Dexter in an example project.

2. Creating New Project

1. Create a new project in Android Studio from File ⇒ New Project and select Basic Activity from templates.

2. Add Dexter dependency to your build.gradle

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    // ...
 
    // Dexter runtime permissions
    implementation 'com.karumi:dexter:4.2.0'
}

3. Open the layout file of your main activity (activity_main.xml and content_main.xml) and add two buttons to test different permission methods.

content_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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="info.androidhive.dexterpermissions.MainActivity"
    tools:showIn="@layout/activity_main">
 
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:orientation="vertical"
        android:layout_centerHorizontal="true"
        android:paddingLeft="16dp"
        android:paddingRight="16dp">
 
        <Button
            android:id="@+id/btn_camera"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="16dp"
            android:text="CAMERA PERMISSION" />
 
        <Button
            android:id="@+id/btn_storage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="MULTIPLE PERMISSIONS" />
 
    </LinearLayout>
</RelativeLayout>

4. Open MainActivity.java and do the modification as shown below.

> requestStoragePermission() requests for camera permission.

> requestStoragePermission() requests multiple permissions at once.

> response.isPermanentlyDenied() and report.isAnyPermissionPermanentlyDenied() checks if the permission is denied permanently. Here we have to navigate user to app settings screen by showing a dialog.

app settings
    private void openSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 101);
    }
 
    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 100);
    }
}

Android Bottom Navigation stays at the bottom of the screen providing navigation between top-level views in the app. This is introduced in design support library with backward compatibility. Bottom Navigation should be used when the app has three to five top-level navigations.

This article explains the basics of Bottom Navigation, combining it with Fragments. We also going to learn how to load the first fragment with grid data (using RecyclerView) by fetching JSON through HTTP call.

1. Bottom Navigation

The Bottom Navigation can be easily added using BottomNavigationView component. You have to use gravitation or relative attributes to make it appear at the bottom of the screen.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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">
 
    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
 
    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="?android:attr/windowBackground"
        app:itemBackground="@color/bgBottomNavigation"
        android:foreground="?attr/selectableItemBackground"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white"
        app:menu="@menu/navigation" />
 
</android.support.design.widget.CoordinatorLayout>

Here few important attributes have to noted down.

app:menu — The menu resource file to display the navigation items along with icon and text.
app:itemBackground — Applies background color to bottom navigation.
app:itemTextColor — The text color of bottom navigation item.
app:itemIconTint — The icon color of bottom navigation item.

When to use Bottom Navigation?
As per the design specs, the below navigations should be used depending on the criteria.

> Navigation Drawer – Use when top-level navigation has more than six destinations.

> Tabs – Use when there are two navigational destinations.

> Bottom Navigation – Use when there are three to five top-level destinations.

Before going further, have a quick look at the design specifications of Bottom Navigation.

Now let’s try it by creating a new project in Android Studio.

2. Creating New Project

1. Create a new project in Android Studio from File ⇒ New Project and select Basic Activity from templates.

2. Download this res folder and add the drawables to your project’s res. This folder contains necessary drawables required for bottom navigation items.

3. Make sure you have design support library in your build.gradle.

build.gradle
dependencies {
    implementation 'com.android.support:design:26.1.0'
}

4. Add below color, string values to your colors.xml and strings.xml.

colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#7b4bff</color>
    <color name="colorPrimaryDark">#6539ba</color>
    <color name="colorAccent">#FF4081</color>
    <color name="bgBottomNavigation">#fe485a</color>
</resources>
strings.xml
<resources>
    <string name="app_name">Bottom Navigation</string>
    <string name="title_shop">Shop</string>
    <string name="title_gifts">Gifts</string>
    <string name="title_cart">Cart</string>
    <string name="title_profile">Profile</string>
</resources>

5. As the Bottom Navigation items rendered using a menu file, create a new xml named navigation.xml under res ⇒ menu folder.

navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
 
    <item
        android:id="@+id/navigation_shop"
        android:icon="@drawable/ic_store_white_24dp"
        android:title="@string/title_shop" />
 
    <item
        android:id="@+id/navigation_gifts"
        android:icon="@drawable/ic_card_giftcard_white_24dp"
        android:title="@string/title_gifts" />
 
    <item
        android:id="@+id/navigation_cart"
        android:icon="@drawable/ic_shopping_cart_white_24dp"
        android:title="@string/title_cart" />
 
    <item
        android:id="@+id/navigation_profile"
        android:icon="@drawable/ic_person_white_24dp"
        android:title="@string/title_profile" />
 
</menu>

6. Open the layout file of main activity i.e activity_main.xml and add BottomNavigationView widget. Here we are also adding a FrameLayout to load the Fragments when the navigation item is selected.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="info.androidhive.bottomnavigation.MainActivity">
 
    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
 
    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="?android:attr/windowBackground"
        app:itemBackground="@color/bgBottomNavigation"
        android:foreground="?attr/selectableItemBackground"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white"
        app:menu="@menu/navigation" />
 
</android.support.design.widget.CoordinatorLayout>

7. Now open MainActivity.java and modify it as below.

> Here, OnNavigationItemSelectedListener will be called when the bottom navigation item is selected. For now we are just changing the toolbar title upon selecting the navigation item.

MainActivity.java
package info.androidhive.bottomnavigation;
 
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
 
import info.androidhive.bottomnavigation.fragment.CartFragment;
import info.androidhive.bottomnavigation.fragment.GiftsFragment;
import info.androidhive.bottomnavigation.fragment.ProfileFragment;
import info.androidhive.bottomnavigation.fragment.StoreFragment;
import info.androidhive.bottomnavigation.helper.BottomNavigationBehavior;
 
public class MainActivity extends AppCompatActivity {
 
    private ActionBar toolbar;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        toolbar = getSupportActionBar();
 
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
 
        toolbar.setTitle("Shop");
    }
 
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
 
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment fragment;
            switch (item.getItemId()) {
                case R.id.navigation_shop:
                    toolbar.setTitle("Shop");
                    return true;
                case R.id.navigation_gifts:
                    toolbar.setTitle("My Gifts");
                    return true;
                case R.id.navigation_cart:
                    toolbar.setTitle("Cart");
                    return true;
                case R.id.navigation_profile:
                    toolbar.setTitle("Profile");
                    return true;
            }
            return false;
        }
    };
}

If you run the app, you can see the bottom navigation displayed as shown below.

3. Adding Fragments

As we have the Bottom Navigation ready, let’s see how to switch views when the navigation menu item is selected. This can be done easily by using the Fragments.

Note: ViewPager shouldn’t be used when using Bottom Navigation as per design specs (Avoid using lateral motion to transition between views)

I am creating four fragments named StoreFragmentGiftsFragmentCartFragment and ProfileFragment.

8. Create new Fragment by going to File ⇒ New ⇒ Fragment ⇒ Fragment (Blank) and name it as StoreFragment.java. Likewise create other three fragments too.

9. Open MainActivity.java and modify bottom navigation listener as below to load the fragments in FrameLayout.

> loadFragment() – loads the Fragment into FrameLayout. The same method is called in OnNavigationItemSelectedListener callback by passing appropriate fragment instance.
> The logic needed for specific module goes into appropriate Fragment keeping the MainActivity clean.

MainActivity.java
package info.androidhive.bottomnavigation;
 
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
 
import info.androidhive.bottomnavigation.fragment.CartFragment;
import info.androidhive.bottomnavigation.fragment.GiftsFragment;
import info.androidhive.bottomnavigation.fragment.ProfileFragment;
import info.androidhive.bottomnavigation.fragment.StoreFragment;
import info.androidhive.bottomnavigation.helper.BottomNavigationBehavior;
 
public class MainActivity extends AppCompatActivity {
 
    private ActionBar toolbar;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        toolbar = getSupportActionBar();
 
        // load the store fragment by default
        toolbar.setTitle("Shop");
        loadFragment(new StoreFragment());
    }
 
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
 
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment fragment;
            switch (item.getItemId()) {
                case R.id.navigation_shop:
                    toolbar.setTitle("Shop");
                    fragment = new StoreFragment();
                    loadFragment(fragment);
                    return true;
                case R.id.navigation_gifts:
                    toolbar.setTitle("My Gifts");
                    fragment = new GiftsFragment();
                    loadFragment(fragment);
                    return true;
                case R.id.navigation_cart:
                    toolbar.setTitle("Cart");
                    fragment = new CartFragment();
                    loadFragment(fragment);
                    return true;
                case R.id.navigation_profile:
                    toolbar.setTitle("Profile");
                    fragment = new ProfileFragment();
                    loadFragment(fragment);
                    return true;
            }
 
            return false;
        }
    };
 
    private void loadFragment(Fragment fragment) {
        // load fragment
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.frame_container, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }
 
}

Now if you run the project you can see the fragments loaded when navigation is selected.

4. Implementing ShopFragment – Displaying Items in Grid

Now we’ll see how to implement the first fragment i.e ShopFragment which displays the shop items in a Grid fashion. For demonstration, I have created a sample json which contains few movies for sale. To implement this, all we have to do is, fetch json and display the data in RecyclerView in a grid format. To make the task simpler, follow my other article which explains the same.

10. Open build.gradle and add RecyclerViewCardViewVolley and Glide dependencies.

build.gradle
dependencies {
    // RecyclerView
    compile 'com.android.support:recyclerview-v7:26.1.0'
 
    // CardView
    compile 'com.android.support:cardview-v7:26.1.0'
 
    // volley http library
    implementation 'com.android.volley:volley:1.0.0'
    implementation 'com.google.code.gson:gson:2.6.2'
 
    // glide image library
    implementation 'com.github.bumptech.glide:glide:4.3.1'
}

11. Create a class named MyApplication.java implement the class from Application. This is a singleton class in which volley library will be initiated.

MyApplication.java
package info.androidhive.bottomnavigation.app;
 
import android.app.Application;
import android.text.TextUtils;
 
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
 
public class MyApplication extends Application {
 
    public static final String TAG = MyApplication.class
            .getSimpleName();
 
    private RequestQueue mRequestQueue;
 
    private static MyApplication mInstance;
 
    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }
 
    public static synchronized MyApplication getInstance() {
        return mInstance;
    }
 
    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
 
        return mRequestQueue;
    }
 
    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }
 
    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }
 
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

12. Open AndroidManifest.xml and add MyApplication to <application> tag. We also need INTERNET permission as we gonna make http calls.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.bottomnavigation">
 
    <uses-permission android:name="android.permission.INTERNET"/>
 
    <application
        android:name=".app.MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

13. Open the layout file of StoreFragment i.e fragment_store.xml and add below layout code. Here we are adding the RecyclerView component.

fragment_store.xml
<android.support.v4.widget.NestedScrollView 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:background="#f1f5f7"
    tools:context="info.androidhive.bottomnavigation.fragment.StoreFragment">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
 
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingTop="10dp"
            android:text="New Release Films"
            android:textColor="#111"
            android:textSize="16dp" />
 
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clipToPadding="false"
            android:scrollbars="vertical" />
    </LinearLayout>
</android.support.v4.widget.NestedScrollView>

14. Create an xml layout named store_item_row.xml under res ⇒ layout. This layout file will be used in RecyclerView adapter class to render single item.

store_item_row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
 
    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="@dimen/card_margin"
        android:clickable="true"
        android:elevation="3dp"
        android:foreground="?attr/selectableItemBackground"
        card_view:cardCornerRadius="@dimen/card_album_radius">
 
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
 
            <ImageView
                android:id="@+id/thumbnail"
                android:layout_width="match_parent"
                android:layout_height="@dimen/album_cover_height"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:clickable="true"
                android:scaleType="fitXY" />
 
            <TextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/thumbnail"
                android:lines="2"
                android:paddingLeft="@dimen/album_title_padding"
                android:paddingRight="@dimen/album_title_padding"
                android:paddingTop="@dimen/album_title_padding"
                android:textColor="#111"
                android:textSize="11dp" />
 
            <TextView
                android:id="@+id/price"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/title"
                android:layout_marginRight="10dp"
                android:gravity="right"
                android:paddingBottom="@dimen/songs_count_padding_bottom"
                android:textColor="@color/colorAccent"
                android:textSize="11dp" />
 
        </RelativeLayout>
 
    </android.support.v7.widget.CardView>
</LinearLayout>

15. Create a class named Movie.java. This POJO class will be useful while parsing the json.

Movie.java
package info.androidhive.bottomnavigation;
 
public class Movie {
    String title;
    String image;
    String price;
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public String getImage() {
        return image;
    }
 
    public void setImage(String image) {
        this.image = image;
    }
 
    public String getPrice() {
        return price;
    }
 
    public void setPrice(String price) {
        this.price = price;
    }
}

16. Now open StoreFragment.java and add below code. For simplicity the RecyclerView adapter class StoreAdapter included in the same fragment.

> fetchStoreItems() Method fetches the movies json using Volley and serializes it using Gson.

> StoreAdapter class renders the movies in RecyclerView.

StoreFragment.java
package info.androidhive.bottomnavigation.fragment;
 
 
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
 
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
 
import org.json.JSONArray;
 
import java.util.ArrayList;
import java.util.List;
 
import info.androidhive.bottomnavigation.Movie;
import info.androidhive.bottomnavigation.app.MyApplication;
import info.androidhive.bottomnavigation.R;
 
public class StoreFragment extends Fragment {
 
    private static final String TAG = StoreFragment.class.getSimpleName();
    private static final String URL = "https://api.androidhive.info/json/movies_2017.json";
 
    private RecyclerView recyclerView;
    private List<Movie> movieList;
    private StoreAdapter mAdapter;
 
    public StoreFragment() {
        // Required empty public constructor
    }
 
    public static StoreFragment newInstance(String param1, String param2) {
        StoreFragment fragment = new StoreFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_store, container, false);
 
        recyclerView = view.findViewById(R.id.recycler_view);
        movieList = new ArrayList<>();
        mAdapter = new StoreAdapter(getActivity(), movieList);
 
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(8), true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);
        recyclerView.setNestedScrollingEnabled(false);
 
        fetchStoreItems();
 
        return view;
    }
 
    private void fetchStoreItems() {
        JsonArrayRequest request = new JsonArrayRequest(URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        if (response == null) {
                            Toast.makeText(getActivity(), "Couldn't fetch the store items! Pleas try again.", Toast.LENGTH_LONG).show();
                            return;
                        }
 
                        List<Movie> items = new Gson().fromJson(response.toString(), new TypeToken<List<Movie>>() {
                        }.getType());
 
                        movieList.clear();
                        movieList.addAll(items);
 
                        // refreshing recycler view
                        mAdapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // error in getting json
                Log.e(TAG, "Error: " + error.getMessage());
                Toast.makeText(getActivity(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
 
        MyApplication.getInstance().addToRequestQueue(request);
    }
 
    public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
 
        private int spanCount;
        private int spacing;
        private boolean includeEdge;
 
        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }
 
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item position
            int column = position % spanCount; // item column
 
            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
 
                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item bottom
            } else {
                outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
                outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                if (position >= spanCount) {
                    outRect.top = spacing; // item top
                }
            }
        }
    }
 
    /**
     * Converting dp to pixel
     */
    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }
 
    class StoreAdapter extends RecyclerView.Adapter<StoreAdapter.MyViewHolder> {
        private Context context;
        private List<Movie> movieList;
 
        public class MyViewHolder extends RecyclerView.ViewHolder {
            public TextView name, price;
            public ImageView thumbnail;
 
            public MyViewHolder(View view) {
                super(view);
                name = view.findViewById(R.id.title);
                price = view.findViewById(R.id.price);
                thumbnail = view.findViewById(R.id.thumbnail);
            }
        }
 
 
        public StoreAdapter(Context context, List<Movie> movieList) {
            this.context = context;
            this.movieList = movieList;
        }
 
        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.store_item_row, parent, false);
 
            return new MyViewHolder(itemView);
        }
 
        @Override
        public void onBindViewHolder(MyViewHolder holder, final int position) {
            final Movie movie = movieList.get(position);
            holder.name.setText(movie.getTitle());
            holder.price.setText(movie.getPrice());
 
            Glide.with(context)
                    .load(movie.getImage())
                    .into(holder.thumbnail);
        }
 
        @Override
        public int getItemCount() {
            return movieList.size();
        }
    }
}

Now if you run the app, you can see the ShopFragment displaying the movies in grid manner. Likewise you can implement other fragments too.

5. Hiding Bottom Navigation on Scroll

As per design specs, the Bottom Navigation has to be hidden when the content is scrolled giving more room to content on the screen. To achieve this, we need to attach the BottomNavigationBehavior to Bottom Navigation.

17. Create a class named BottomNavigationBehavior.java with the below code.

BottomNavigationBehavior.java
package info.androidhive.bottomnavigation.helper;
 
import android.content.Context;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
 
public class BottomNavigationBehavior extends CoordinatorLayout.Behavior<BottomNavigationView> {
 
    public BottomNavigationBehavior() {
        super();
    }
 
    public BottomNavigationBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, BottomNavigationView child, View dependency) {
        boolean dependsOn = dependency instanceof FrameLayout;
        return dependsOn;
    }
 
    @Override
    public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, BottomNavigationView child, View directTargetChild, View target, int nestedScrollAxes) {
        return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL;
    }
 
    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, BottomNavigationView child, View target, int dx, int dy, int[] consumed) {
        if (dy < 0) {
            showBottomNavigationView(child);
        } else if (dy > 0) {
            hideBottomNavigationView(child);
        }
    }
 
    private void hideBottomNavigationView(BottomNavigationView view) {
        view.animate().translationY(view.getHeight());
    }
 
    private void showBottomNavigationView(BottomNavigationView view) {
        view.animate().translationY(0);
    }
}

18. Add the BottomNavigationBehavior using setBehavior() in MainActivity.java as shown below.

MainActivity.java
public class MainActivity extends AppCompatActivity {
 
    private ActionBar toolbar;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
 
        // attaching bottom sheet behaviour - hide / show on scroll
        CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) navigation.getLayoutParams();
        layoutParams.setBehavior(new BottomNavigationBehavior());
 
        // load the store fragment by default
        // ..
    }
}

Now if you test the app, you can see the Bottom Navigation sliding down when the app content is scrolled.