In this article, we will learn to load Base64 String Images into Images in Xamarin.Forms without using any External Plugins like FFMpe...

Loading Base64 Images In Xamarin.Forms Loading Base64 Images In Xamarin.Forms

A blog about android developement


In this article, we will learn to load Base64 String Images into Images in Xamarin.Forms without using any External Plugins like FFMpeg Image Loader Plugin.

Base64 Images

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding. To know more about Base64 Click Here.

Platform Support

The approach used here is done with Portable Library. So, it supports all the 3 (Android, iOS, and UWP) Platforms supported by Xamarin.Forms.
Without much introduction, we will skip into the coding part of this article.

Steps

I have explained the method to load base64 image in Image with 3 steps as shown below.
Step 1 - Creating new Xamarin.Forms Projects.
Step 2 - Creating a user interface with Xamarin.Forms.
Step 3 - Implementing the functionality to load Base64 Image.
Step 1 Creating new Xamarin.Forms Projects.
Create New Project by Selecting New >> Project >> Select Xamarin Cross-Platform App and Click OK.
Xamarin
Then Select Android and iOS Platforms as shown below with Code Sharing Strategy as PCL or .NET Standard and Click OK.
Xamarin
Step 2 Creating a user interface with Xamarin.Forms
Add Image Control to your Page, and here, I am going to add the control in MainPage.xaml. You can paste the codes shown below to create user interface for your page.
<?xml version="1.0" encoding="utf-8" ?>  
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
 xmlns:local="clr-namespace:Base64" 
 x:Class="Base64.MainPage">  
    <ContentPage.Content>  
        <Image x:Name="xfImage" 
   VerticalOptions="Center"
   HorizontalOptions="Center" /> 
 </ContentPage.Content>  
</ContentPage>
Step 3 implementing the functionality to load Base64 Image
In Xamarin.Forms, we can assign the source for Images by many ways like File Path, Image URL, From Resource Folder or Stream of Image.
We can convert the Base64 string into Stream of Image. That is array of Bytes (byte[]). We will use this method to assign Base64 image to Image Controls using the following code.
byte[] Base64Stream = Convert.FromBase64String(base64Image);  
xfImage.Source = ImageSource.FromStream(() => new MemoryStream(Base64Stream));
Full Code of MainPage.xaml.cs
namespace Base64 {  
    public partial class MainPage: ContentPage {  
        string base64Image = "iVBORw0KGgoAAAANSUhEUgAAAHwAAAB8CAMAAACcwCSMAAAAZlBMVEUAAAD///+cnJz7+/vz8/MdHR329vbw8PBRUVHh4eEaGhqsrKzn5+dZWVnk5OQyMjLZ2dmOjo6ysrIoKCjR0dFiYmKjo6NKSkoNDQ3ExMQ4ODi5ubmHh4cWFhbLy8tBQUF6enpvb2/Qp8GOAAAFzUlEQVRogcWb56KyOhBFIyBFQUGkiQXe/yVvQPFQUvYEvN/+q7CYlMnMJGG7fyhm8pDrnZ71Mbd65cf6efLc/wPuhlXeRLf0wUZ6pLeoyauQ+gUkuFPd/ZRJlfr3yvkN3L20pRw8qGwvuP0g3K0aPXhQU4F8CB5aLxzd6WWFG8HDRNHPMqUJgNfCPRP0G++thNtHQ3SPP9pr4NfCHN2puBrDvWYdulOjansFvLqtZzN2qwzgtrUFupMl7XkZPGy3YjPWymadBB4TvYpar5gCrwEvTlFZ4/DjtuhORxT+A7aYLoD/hC2kL+E/YovoC/jlV2zGLjr483dsxp5qeLBiEdMrDVRwz/8lmzHfU8DvlDelLz/yX7SmusvhhIEe5XHYLRh2GOcRgX6UwWPUqT6s08SCUwK74zKWwFELmuUqFTYoPRLDwQX8JY4O6jNIt0Tw00P/IJcvWR53MThTHn9d9gdvoEezQAR+Nz1Ib5bwK/TgSxUPBmDQ9w1pB7gNffZDbndvANhzQ1A3wGvoMUuG/SiH3sKGuOYDd6FpVuiybxtLMiJ3AscMX6yJC4ELcj2BQ4b7+rKDg425aAzHhrquxzsl0Js+A/4Nb5AHynksIFKFefnmD25DD9y0+TbXCfSy9heODbcIqbQ44OpUf+EZ9P9GjX3LbjB4NsA97P8JAoeDIe8DBycnMtjh4d77jA4OZsPbWt6+4R44QLE+R/P6s9fD0Txh09HeZxAMXoq2neeM5T0cLoBs6OFY3+ls58AVkA19O9fL4fATnHP4+nb38FpOeuJwvKGA9Rxz1L3KisMJOVKhqaXudpQi1pHDKcU+nZ8hFQ4tDm8I/3/IMoa3CD3IOqfF4AytV6Eq4RMrhxGH057I5PSQZAafaxxOLIQUsrwhoNbm0x2z99RnJFkquWK6t+lwVjZL44OG+hZDODf+PsXHd4OXmMK59ZEV9Ju3rhfnkVmN2hjeKS2yNivMC3er4Gv1r+E7OPSYqTy//CiLipvp15+5kyHv2z3SqLWqZ8xHnG27Thhfq2PTFlhVYqSCw7F0ZdA+S56xIJK0w+ulIXpqDqfUW8/WVRXCnmqKJXcOR4NX7lrUO6O9wiNcuM45HIx8brN6q1R2lWHdX3P49QD88ZCA6E5ujVh/uHK4B5RRsqc2eps2vqW3iOcgbGdrY4CDcEdOrUA79CK7y1h0cX5GaPGRjhrjkz5d0qTnidHJI66ruj8vPTxQfmJuiOYKVOPuEPRwV/Uf8fYvKE8xnHz3XZmQd3qpT5CUUmTrXf7RweX1xxVt/rFdumxdP3BbtqpiVRilZFuUZ/sDl7V7azrOx6oUdvXwQPxx6m0FVGLLgi9cnDIZ+DWRhFXw1+4PLlpWXzR3LpfIieUjuCMYFqtm+ETLdk2dEVzQMe1mbEHE8JlGH/hiRpSKI01UufMVbtjEH7a25pFcgVT8UM3LPsMu+gAPHuLfN1E8bdfv1uB3O3PW6xu2+qLdv47zC3cmPvYBBKoENeN3n787ZH+7yJMxuVeXnaiajKi/OTzavB8vf4dNLZ9svIyODozg8XjMyY/vGSgYuZlxKW98ZmJcPyxbazMlY+8+Ll1PjqrQckYjZTsZPDTN1WGdQymcWDyla+a0Zwez4JTVTLOYcH4krfkle745tjiM98NzYf6ctYA7P6MvDx4sz0CiZ23I7GWxXHD68/QTui/IdUXnXsOVp9pFEm5RCE/8KlNHI/nC/ENy0Jp0HlEvSVwkgdv5hr6ulKUf0sP1z838/Fm6ASy/VqDK7CmK5HGw6kJFTq7lLvVQpfjKqySn1Qu8upKluURTr7rRcdPke7rrQ45lvImSWrpTZPqLU0b3prCbU8iVsZBufQrdGcMuy7kX0ryLwNt68DXB0ALH3g27KEeCc5cbW5FmJ2kfWTEh26BdDbXDOsluwlrt4ZYldUjLc+iXYm0vrvOk9c/7Q6/92W+TvI49eoJldCP38xUfmb/hPxbhSmN+ggQuAAAAAElFTkSuQmCC";  
        public MainPage() {  
            InitializeComponent();  
            byte[] Base64Stream = Convert.FromBase64String(base64Image);  
            xfImage.Source = ImageSource.FromStream(() => new MemoryStream(Base64Stream));  
        }  
    }  
}
The longest string shown here is the base 64 is encoded to the image
  • Convert.FromBase64String(base64Image) is used to convert base64 string byte[].
  • ImageSource.FromStream(() => new MemoryStream(Base64Stream)) is used to convert the byte[] to Image Stream and Stream is assigned to Image Control.

When considering how to build iOS and Android applications, many people think that the native languages, Objective-C, Swift, and Java, ...

Xamarin - Introduction Xamarin - Introduction

A blog about android developement


When considering how to build iOS and Android applications, many people think that the native languages, Objective-C, Swift, and Java, are the only choice. However, over the past few years, an entire new ecosystem of platforms for building mobile applications has emerged.

Xamarin is unique in this space by offering a single language – C#, class library, and runtime that works across all three mobile platforms of iOS, Android, and Windows Phone (Windows Phone’s native language is already C#), while still compiling native (non-interpreted) applications that are performant enough even for demanding games. 

Each of these platforms has a different feature set and each varies in its ability to write native applications – that is, applications that compile down to native code and that interop fluently with the underlying Java subsystem. For example, some platforms only allow apps to be built in HTML and JavaScript, whereas some are very low-level and only allow C/C++ code. Some platforms don’t even utilize the native control toolkit.  

In Androidmads, we will not cover the basics of Xamarin App development. But, we will cover the advanced concepts of Xamarin as well as we will assist you, if you find any help with Xamarin Basics. And also we will see about Flutter App development.

Introduction: In this article, we will learn how to create and use Clearable EditText without using any Third party library. It is very e...

Clearable EditText in Android Clearable EditText in Android

A blog about android developement

Introduction:

In this article, we will learn how to create and use Clearable EditText without using any Third party library. It is very easy to implement and useful control for our application development.

Coding Part:

Steps:

I have split this part into 3 steps as in the following.
  1. Creating New Project with Empty Activity.
  2. Setting up the Library.
  3. Implementation of Custom Control in Android.

Step 1: Creating New Project with Android Studio

  1. Open Android Studio and Select Create new project.
  2. Name the project as your wish and select your activity template.
  3. Click “finish” button to create new project in Android Studio.

Step 2: Setting up the Firebase Library

In this part, we will see how to setup the library for the project.
  1. Open your app level build.gradle file and add the following lines in dependencies to apply required libraries to your project.
    dependencies {
        ...
        implementation 'com.android.support:appcompat-v7:26.1.0'
        implementation 'com.android.support.constraint:constraint-layout:1.1.2'
        implementation 'com.android.support:support-annotations:27.1.1'
        implementation 'com.android.support:design:26.1.0'
    }
  2. Then click “Sync Now” to setup your project.

Step 3: Implementation of Clearable EditText:

Create a class named as ClearableEditText extend with AppCompatEditText as Parent. Then open the class file and add the following code of lines.

public class ClearableEditText extends android.support.v7.widget.AppCompatEditText {

    private Drawable drawableTemp;
    private Drawable drawableRight;

    int actionX, actionY;

    private DrawableClickListener clickListener;

    public ClearableEditText(Context context) {
        super(context);
    }

    public ClearableEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ClearableEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    public void setCompoundDrawables(Drawable left, Drawable top,
                                     Drawable right, Drawable bottom) {
        if (right != null) {
            drawableRight = right;
        }
        super.setCompoundDrawables(left, top, right, bottom);
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        if (text.toString().length() > 0) {
            drawableRight = drawableTemp;
            setCompoundDrawables(null, null, drawableRight, null);
        } else {
            drawableTemp = drawableRight;
            setCompoundDrawables(null, null, null, null);
        }
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Rect bounds;
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            actionX = (int) event.getX();
            actionY = (int) event.getY();
            if (drawableRight != null) {

                bounds = drawableRight.getBounds();
                int x, y;
                int extraTapArea = 13;

                /*
                  IF USER CLICKS JUST OUT SIDE THE RECTANGLE OF THE DRAWABLE
                  THAN ADD X AND SUBTRACT THE Y WITH SOME VALUE SO THAT AFTER
                  CALCULATING X AND Y CO-ORDINATE LIES INTO THE DRAWBABLE
                  BOUND. - this process help to increase the tappable area of
                  the rectangle.
                 */
                x = actionX + extraTapArea;
                y = actionY - extraTapArea;

                /*
                 Since this is right drawable subtract the value of x from the width
                 of view. so that width - tapped_area will result in x co-ordinate in drawable bound.
                */
                x = getWidth() - x;

                 /*x can be negative if user taps at x co-ordinate just near the width.
                  e.g views width = 300 and user taps 290. Then as per previous calculation
                  290 + 13 = 303. So subtract X from getWidth() will result in negative value.
                  So to avoid this add the value previous added when x goes negative.
                 */

                if (x <= 0) {
                    x += extraTapArea;
                }

                 /*
                 If result after calculating for extra tap-able area is negative.
                 assign the original value so that after subtracting
                 extra tapping area value doesn't go into negative value.
                 */

                if (y <= 0)
                    y = actionY;

                /*
                If drawable bounds contains the x and y points then move ahead.
                */
                if (bounds.contains(x, y) && clickListener != null) {
                    clickListener.onClick();
                    event.setAction(MotionEvent.ACTION_CANCEL);
                    return false;
                }
                return super.onTouchEvent(event);
            }

        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void finalize() throws Throwable {
        drawableRight = null;
        super.finalize();
    }

    public void setDrawableClickListener(DrawableClickListener listener) {
        this.clickListener = listener;
    }

    public interface DrawableClickListener {
        void onClick();
    }
}

Here, I have created DrawableClickListener interface which is used to intimate users when they clicked the Drawable icon of the EditText control.

Open your activity_main.xml file and add the following lines.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_margin="10dp"
    tools:context="com.androidmads.materialedittext.MainActivity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/text_input_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:errorEnabled="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.androidmads.materialedittext.ClearableEditText
            android:id="@+id/edit_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableEnd="@drawable/ic_close"
            android:drawableRight="@drawable/ic_close"
            android:hint="Enter your name" />

    </android.support.design.widget.TextInputLayout>

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="68dp"
        android:text="Click Here..."
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/text_input_layout" />

</android.support.constraint.ConstraintLayout>

The Layout Preview looks like in the below screenshot

This control will shows the cancel “icon” when the control has typed text and “icon” will hide when the control has no text. Then open your MainActivity.java file and initialize your control like the following.

final TextInputLayout textInputLayout = findViewById(R.id.text_input_layout);
final ClearableEditText editText = findViewById(R.id.edit_text);
final Button button = findViewById(R.id.button);
The cancel icon will appear when the user types the data. Add the following Drawable click listener as look like in the following.
editText.setDrawableClickListener(new ClearableEditText.DrawableClickListener() {
 @Override
 public void onClick() {
  editText.setText(null);
 }
});

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

As discussed in our previous posts, we have learned how to perform email authentication and phone number authentication with firebase i...

Firebase Google plus Authentication in Android Firebase Google plus Authentication in Android

A blog about android developement

As discussed in our previous posts, we have learned how to perform email authentication and phone number authentication with firebase in android. In this article, we will how to perform Google Plus authentication in Android.

You can find my previous posts from following,

  1. Firebase Email Authentication

  2. Firebase Phone Authentication

Firebase G-Plus Authentication:

Firebase facilities Developers to manage Google plus Authentication in Easy way. Before starting, we have add or enable Google plus Authentication in Firebase console.

Firebase Setup:

Before start coding, we have to setup firebase for android and enable Phone Authentication. If you are new to firebase, the following link will be useful to know the method for setting up the project in firebase.

After setting up, open Authentication sign in method and enable phone authentication method as shown in the following figure.

You should Add SHA Fingerprint in your application. The following terminal will be used to get the SHA Fingerprint with Command Prompt in Windows for debug mode.

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

Coding Part:

Steps:

I have split this part into 3 steps as in the following.

Step 1: Creating New Project with Empty Activity.

Step 2: Setting up the Firebase Library.

Step 3: Implementation of Firebase Google Plus Authentication.

Step 1: Creating New Project with Android Studio

  1. Open Android Studio and Select Create new project.

  2. Name the project as your wish and select your activity template.


  3. Click “finish” button to create new project in Android Studio.

Step 2: Setting up the Firebase Library

In this part, we will see how to setup the library for the project.

  1. Open your project level build.gradle file and add the following lines in dependencies.

    dependencies {
        …
        classpath 'com.google.gms:google-services:4.0.1'
        …
    }
  2. Then add the following lines in allprojects in project level build.gradle file.

    allprojects {
        repositories {
            google()
            jcenter()
            maven {
                url "https://maven.google.com"
            }
        }
    }
  3. Then add the following lines in app level build.gradle file to apply google services to your project.

    dependencies {
        ...
        implementation 'com.google.firebase:firebase-auth:16.0.2'
        implementation 'com.google.android.gms:play-services-auth:15.0.1'
        implementation 'com.squareup.picasso:picasso:2.71828'
    }
    apply plugin: 'com.google.gms.google-services'
  4. Then click “Sync Now” to setup your project.

Step 3: Implementation of Firebase Google plus Authentication:

Initialize Google Sign in Client with Google Sign in options and Firebase Auth Client like shown in below snippet.

//first we initialized the Firebase Auth object
FirebaseAuth mAuth = FirebaseAuth.getInstance();

//Then we need a GoogleSignInOptions object
//And we need to build it as below
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  .requestIdToken(getString(R.string.default_web_client_id))
  .requestEmail()
  .build();

//Then we will get the GoogleSignInClient object from GoogleSignIn class
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

You must pass your server's client ID to the requestIdToken method. To find the OAuth 2.0 client ID: Open the Credentials page in the API Console. The Web application type client ID is your backend server's OAuth 2.0 client ID.

Then add the following code to initiate Google sign in.

//getting the google signin intent
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
//starting the activity for result
startActivityForResult(signInIntent, RC_SIGN_IN);

Add the onActivityResult as shown below

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

 //if the requestCode is the Google Sign In code that we defined at starting
 if (requestCode == RC_SIGN_IN) {

  //Getting the GoogleSignIn Task
  Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
  try {
   //Google Sign In was successful, authenticate with Firebase
   GoogleSignInAccount account = task.getResult(ApiException.class);
   //authenticating with firebase
   firebaseAuthWithGoogle(account);
  } catch (ApiException e) {
   Log.v("API Exception", e.toString());
   Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
  }
 }
}

After a user successfully signs in, get an ID token from the GoogleSignInAccount object, exchange it for a Firebase credential, and authenticate with Firebase using the Firebase credential.

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
 Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

 //getting the auth credential
 AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);

 //Now using firebase we are signing in the user here
 mAuth.signInWithCredential(credential)
                            .addOnCompleteListener(this, new OnCompleteListener() {
  @Override
  public void onComplete(@NonNull Task task) {
   if (task.isSuccessful()) {
    if (mAuth.getCurrentUser() != null) {
     startActivity(new Intent(LoginActivity.this, MainActivity.class));
     finish();
    }
   } else {
    // If sign in fails, display a message to the user.
    Log.w(TAG, "signInWithCredential:failure", task.getException());
    Toast.makeText(LoginActivity.this, "Authentication failed.",
     Toast.LENGTH_SHORT).show();
   }
  }
 });
}

If the user is authenticated with Google Plus Sign In successfully, then login screen is redirected to the next activity.

To retrieve user details like name, profile picture, mail id through Firebase, use the following snippets.

FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();

assert user != null;
textName.setText(user.getDisplayName());
textEmail.setText(user.getEmail());

Picasso.get().load(user.getPhotoUrl()).into(imageView);

Here, I have used Picasso Image Loading Library to load images. To more click here.

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

Introduction: In this article, we will learn how use Kenburnsview in Android using Kotlin. Kenburnsview is an awesome Android library ...

How to use KenburnsView in Kotlin How to use KenburnsView in Kotlin

A blog about android developement

Introduction:

In this article, we will learn how use Kenburnsview in Android using Kotlin. Kenburnsview is an awesome Android library that provides an extension to ImageView that creates an immersive experience by animating its Drawable using the Ken Burns Effect.

Coding Part:

I have divided the coding part into 3 steps as shown in the following.

  1. Creating new project with Kotlin Support.

  2. Setting up the project with Kenburnsview Library.

  3. Implementing KenburnsView with Kotlin.

Step 1: Creating new project with Kotlin:

  1. Open Android Studio and Select Create new project.

  2. Name the project as your wish and tick the Kotlin checkbox support.

  3. Then Select your Activity type (For Example: Navigation Drawer Activity, Empty Activity, etc.).

  4. Then Click “finish” button to create new project in Android Studio.

Step 2: Setting up the project with AndroidManifest:

We will add the following lines to your app level build.gradle to add KenburnsView library to your project.

dependencies { 
    …
    implementation 'com.flaviofaria:kenburnsview:1.0.7'
    …
}
repositories {
    mavenCentral()
}

Step 3: Implementation of KenburnsView with Kotlin

  1. We will start coding. Open your layout file. In my case, I have activity_main.xml included content_main.xml. So, I have opened content_main.xml.

  2. Then add the following lines.

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.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"
              app:layout_behavior="@string/appbar_scrolling_view_behavior"
              tools:context="com.androidmads.kenburnsview.MainActivity"
              tools:showIn="@layout/activity_main">
    
        <com.flaviofaria.kenburnsview.KenBurnsView
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/img"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/img1" />
    
    </android.support.constraint.ConstraintLayout>
  3. Then open your MainActivity.java file and Initialize the KenburnsView Library as shown in the following.

    var mImg: KenBurnsView? = null
    mImg = findViewById(R.id.img)
  4. We can pause, resume and stop the ken burns effect by the library itself using the following snippets respectively.

    mImg!!.pause()
    mImg!!.resume()
    mImg!!.stop()
  5. We can perform our defined operations based on the transitions of KenburnsView using the following snippets.

    mImg!!.setTransitionListener(object : KenBurnsView.TransitionListener {
     override fun onTransitionStart(transition: Transition) {
    
     }
    
     override fun onTransitionEnd(transition: Transition) {
      if (imageId == R.drawable.img1) {
       imageId = R.drawable.img2
       mImg!!.setImageResource(R.drawable.img2)
      } else {
       imageId = R.drawable.img1
       mImg!!.setImageResource(R.drawable.img1)
      }
     }
    })
  6. Here, I have changed the image source to KenburnsView, when each image transitions end.

Full Code of MainActivity:

You can find the full code implementation of MainActivty.kt in the following

class MainActivity : AppCompatActivity() {

    private var mImg: KenBurnsView? = null
    private var fab: FloatingActionButton? = null
    private var isPlaying = true
    private var imageId: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        imageId = R.drawable.img1

        fab = findViewById(R.id.fab)
        mImg = findViewById(R.id.img)

        fab!!.setOnClickListener {
            if (isPlaying) {
                mImg!!.pause()
                fab!!.setImageResource(R.drawable.ic_play)
            } else {
                mImg!!.resume()
                fab!!.setImageResource(R.drawable.ic_pause)
            }
            isPlaying = !isPlaying
        }

        mImg!!.setTransitionListener(object : KenBurnsView.TransitionListener {
            override fun onTransitionStart(transition: Transition) {

            }

            override fun onTransitionEnd(transition: Transition) {
                if (imageId == R.drawable.img1) {
                    imageId = R.drawable.img2
                    mImg!!.setImageResource(R.drawable.img2)
                } else {
                    imageId = R.drawable.img1
                    mImg!!.setImageResource(R.drawable.img1)
                }
            }
        })
    }
}

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

Introduction: In this article, we will learn how to create a music previewer like Google play music and register the app as Music Play...

How to Create a Music Previewer in Android How to Create a Music Previewer in Android

A blog about android developement

musicpreviewer
Introduction:
In this article, we will learn how to create a music previewer like Google play music and register the app as Music Player to the phone. Registering mobile app as Music Player will show our app in suggestions while opening audio files.
Intent Filter:
Registering app as music player will be achieved by intent-filters in AndroidManifest.xml against our activity. To know more about Intent-Filters, read the link.
Coding Part:
Steps:
I have split this part into 3 steps as in the following.
Step 1: Creating New Project with Empty Activity.
Step 2: Implementation of Music Previewer UI.
Step 3: Setting up Manifest with Intent Filters.
Step 4: Implementation of Music Previewer in Android.
Step 1: Creating New Project with Android Studio
  1. Open Android Studio and Select Create new project.
  2. Name the project as your wish and select your activity template.
  3. Click “finish” button to create new project in Android Studio.
Step 2: Implementation of Music Previewer UI
In this part, we will see how to create a dialog for music previewer.
  1. We will create an activity named as MainActivity.java and we need this activity to be show like Dialog. So, we have add the following lines in styles.xml file.
    <resources>
    
        <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.Light.Dialog">
            <item name="windowNoTitle">true</item>
            <item name="colorPrimary">@color/colorPrimary</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="colorAccent">@color/colorAccent</item>
            <item name="windowMinWidthMajor">90%</item>
            <item name="windowMinWidthMinor">90%</item>
            <item name="android:windowCloseOnTouchOutside">false</item>
        </style>
    
    </resources>
  2. Theme.Appcompat.Light.Dialog is used to apply dialog like style to an activity.
  3. By default, the dialog style applied based on children width. To apply full width to the dialog, use windowMinWidthMinor key with value 90%.
  4. In the same way, windowCloseOnTouchOutside is used to handle dialog cancel on touch outside of the views. It is similar setCancelableOnTouchOutside method for dialogs.
  5. Then open your layout file (for example: activity_main.xml) and add the followings lines.
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_margin="10dp"
        android:background="@android:color/white"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:padding="10dp"
        tools:context=".MainActivity">
    
            <ImageView
                android:id="@+id/song_art"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:scaleType="fitXY"
                android:contentDescription="@string/image_desc"
                android:src="@mipmap/ic_launcher" />
    
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="9"
                android:orientation="vertical"
                android:paddingLeft="10dp"
                android:paddingStart="10dp"
                tools:ignore="RtlSymmetry">
    
                <TextView
                    android:id="@+id/song_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/tv_song_title" />
    
                <TextView
                    android:id="@+id/song_artist"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:text="@string/tv_song_artist" />
            </LinearLayout>
    
            <ImageView
                android:id="@+id/play_pause"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:contentDescription="@string/image_desc"
                android:src="@drawable/ic_play" />
    
    </LinearLayout>
  6. Your layout shown like in the following figure.
    scrn 1
  7. Then click Run to view the output activity as dialog in the following figure.
scrn 2
Step 3: Setting up manifest with Intent-Filter:
In this step, we will learn How to apply intent-filter to register your music player app. The following line of codes will help us to register the app.
<activity android:name=".MainActivity">
 <intent-filter>
  <action android:name="android.intent.action.MAIN" />

  <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 <intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <data android:scheme="file"/>
  <data android:mimeType="audio/*"/>
 </intent-filter>
</activity>
This filters will lead the app to be in suggestions when we opening/selecting any audio files. The following figure for your reference.
scrn 3
Step 4: Implementation of Music Previewer in Android.
In this step, we will how to handle media options using Media Player API in Android (i.e., play, pause…).
  1. Media Player can be initialized as shown in the following.
    MediaPlayer mp = new MediaPlayer();
  2. The selected song’s path can be get using Intent and activity opening option can be identified with its action.
    if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
      try {
       assignSongDetails(getIntent().getData().getPath());
       mp.setDataSource(getIntent().getData().getPath());
       mp.prepare();
       mp.start();
      } catch (Exception e) {
       e.printStackTrace();
      }
     }
  3. Selected song can be played with start method in media player API.
    mp.start();
  4. Media Player can be paused using pause method in media player API.
    if (mp.isPlaying()) {
      mp.pause();
     }
     
  5. Then click Run or Shift + F10 to deploy the app in debug mode. Close your app and select any audio file you want to open and select your app. Now you can find your music player works fine.
  6. Next we will see, how to get the details of the selected audio file. MediaMetadataRetriever is used here.
  7. The MediaMetaDataRetriever can be initialized like below.
    metaRetriever = new MediaMetadataRetriever();
     metaRetriever.setDataSource(filePath);
  8. Song’s album can be retrieved using the following code.
    metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
  9. Song’s artist can be retrieved using the following code.
    metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
  10. In the same way, we can read the album art using the following method.
    byte[] art = metaRetriever.getEmbeddedPicture();
     Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
     imgSongArt.setImageBitmap(songImage);
     
  11. The media player can be stopped using stop method in media player API with onPause method of the activity.
    @Override
     protected void onPause() {
      super.onPause();
      assert mp != null;
      if (mp.isPlaying()) {
       mp.stop();
      }
     }
    scrn 4
    Full Code:
    You can find the full code implementation here.
    public class MainActivity extends AppCompatActivity {
    
        TextView tvSongTitle, tvSongArtist;
        ImageView playPause, imgSongArt;
        MediaPlayer mp = new MediaPlayer();
    
        MediaMetadataRetriever metaRetriever;
        byte[] art;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            tvSongTitle = findViewById(R.id.song_title);
            tvSongArtist = findViewById(R.id.song_artist);
            playPause = findViewById(R.id.play_pause);
            imgSongArt = findViewById(R.id.song_art);
    
            if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
                try {
                    assignSongDetails(getIntent().getData().getPath());
                    mp.setDataSource(getIntent().getData().getPath());
                    mp.prepare();
                    mp.start();
                    playPause.setImageResource(R.drawable.ic_pause);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
            playPause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mp.isPlaying()) {
                        mp.pause();
                        playPause.setImageResource(R.drawable.ic_play);
                    } else {
                        mp.start();
                        playPause.setImageResource(R.drawable.ic_pause);
                    }
                }
            });
    
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {
                    playPause.setImageResource(R.drawable.ic_play);
                }
            });
    
        }
    
        void assignSongDetails(String filePath) {
            metaRetriever = new MediaMetadataRetriever();
            metaRetriever.setDataSource(filePath);
            try {
                tvSongTitle.setText(metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
                tvSongArtist.setText(metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
                try {
                    art = metaRetriever.getEmbeddedPicture();
                    Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
                    imgSongArt.setImageBitmap(songImage);
                } catch (Exception ex) {
                    imgSongArt.setImageResource(R.mipmap.ic_launcher);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            assert mp != null;
            if (mp.isPlaying()) {
                mp.stop();
            }
        }
    }
Download Code:
You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

Introduction:  In this article, we will learn how to generate QR Code in Android. Quick Response Code (QR Code in short) is a 2-Dimensi...

How To Generate QR Code In Android How To Generate QR Code In Android

A blog about android developement

QR-CODE  GENERATOR - Library

Introduction: 

In this article, we will learn how to generate QR Code in Android. Quick Response Code (QR Code in short) is a 2-Dimensional matrix type barcode used to store data. It is more popular because of its storage capacity and fast readability.

Zxing & QR Generator Library:

Zebra Crossing (Zxing) is an awesome library used to generate and read QR codes in mobile apps. But it is bigger in size. So, we have to go for another one, QR Generator which is a tiny, open source library. In this article, we will learn how to create & save the QR Code in Android programmatically.

Steps:

I have split this part into 4 steps as in the following.
  1. Creating a New Project with Empty Activity.
  2. Setting up the library and manifest.
  3. Generating QR Code.
  4. Saving QR Code.

Step 1 - Creating New Project with Empty Activity

  1. Open Android Studio and Select create a new project.
  2. Name the project as per your wish and select an Empty activity.
    Android
  3. Click finish button to create a new project in Android Studio.

Step 2 - Setting up the library and manifest

  1. Open App level gradle file and import the library.
    implementation 'androidmads.library.qrgenearator:QRGenearator:1.0.3'
  2. The, click “Sync Now”.
  3. Then, open your Manifest file and add the following permissions. It is used to save QR Code to file storage.
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  4. We need to handle runtime permissions from Android Version 6.0.

Step 3 - Generating QR Code

In this step, we will learn how to generate QR Code in Android. Open your MainActivity.java file and add the following lines.
QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension);
      - Here, inputValue is an input to be converted to QR Code.
      - Input Type also can be specified while initializing the library.
      - We can specify the dimensions also.
    Then, add the following lines to create QR Code and encode that into Bitmap Format.
    try {  
      // Getting QR-Code as Bitmap  
      bitmap = qrgEncoder.encodeAsBitmap();  
      // Setting Bitmap to ImageView  
      qrImage.setImageBitmap(bitmap);  
    } catch (WriterException e) {  
      Log.v(TAG, e.toString());  
    }
    qrImage is an ImageView used to preview the generated QR code bitmap.

Step 4 - Saving QR Code

QR Generator has an option to save the generated QR Code Bitmap to storage using the following lines.
// Save with location, value, bitmap returned and type of Image(JPG/PNG).  
QRGSaver.save(savePath, edtValue.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);
We can save QR Code in PNG & JPG format also. We have to handle runtime permissions from Android version 6.0.

Full Code

You can find the full code implementation here.
public class MainActivity extends AppCompatActivity {  
  
    String TAG = "GenerateQRCode";  
    EditText edtValue;  
    ImageView qrImage;  
    Button start, save;  
    String inputValue;  
    String savePath = Environment.getExternalStorageDirectory().getPath() + "/QRCode/";  
    Bitmap bitmap;  
    QRGEncoder qrgEncoder;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  
        qrImage = (ImageView) findViewById(R.id.QR_Image);  
        edtValue = (EditText) findViewById(R.id.edt_value);  
        start = (Button) findViewById(R.id.start);  
        save = (Button) findViewById(R.id.save);  
  
        start.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View view) {  
                inputValue = edtValue.getText().toString().trim();  
                if (inputValue.length() > 0) {  
                    WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);  
                    Display display = manager.getDefaultDisplay();  
                    Point point = new Point();  
                    display.getSize(point);  
                    int width = point.x;  
                    int height = point.y;  
                    int smallerDimension = width < height ? width : height;  
                    smallerDimension = smallerDimension * 3 / 4;  
  
                    qrgEncoder = new QRGEncoder(  
                            inputValue, null,  
                            QRGContents.Type.TEXT,  
                            smallerDimension);  
                    try {  
                        bitmap = qrgEncoder.encodeAsBitmap();  
                        qrImage.setImageBitmap(bitmap);  
                    } catch (WriterException e) {  
                        Log.v(TAG, e.toString());  
                    }  
                } else {  
                    edtValue.setError("Required");  
                }  
            }  
        });  
  
        save.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                boolean save;  
                String result;  
                try {  
                    save = QRGSaver.save(savePath, edtValue.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);  
                    result = save ? "Image Saved" : "Image Not Saved";  
                    Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        });  
  
    }  
}

Download Code

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub.

Introduction: In this article, we will learn how perform AsyncTask in android with Kotlin. Async task is used to perform some async...

How to do AsyncTask in Kotlin How to do AsyncTask in Kotlin

A blog about android developement

kotlin_async
Introduction:
In this article, we will learn how perform AsyncTask in android with Kotlin. Async task is used to perform some asynchronous tasks without blocking the main thread. It is very useful in android development. Similar to java, the same code can be used in Kotlin with some minor modifications.
Coding Part:
I have divided the coding part into 3 steps as shown in the following.
  1. Creating new project with Kotlin Support.
  2. Setting up the project with AndroidManifest.
  3. Implementing Async tasks with Kotlin.
Without any delay, we will start coding for Kotlin AsyncTask.
Step 1: Creating new project with Kotlin:
  1. Open Android Studio and Select Create new project.
  2. Name the project as your wish and tick the Kotlin checkbox support.
  3. Then Select your Activity type (For Example: Navigation Drawer Activity, Empty Activity, etc.).
  4. Then Click “finish” button to create new project in Android Studio.
Step 2: Setting up the project with AndroidManifest:
Now, we will add the internet permission in Android Manifest file. Because we will see the example with URL Connection. Just open your AndroidManifest.xml file and add the following line.
<uses-permission android:name="android.permission.INTERNET"/>
Step 3: Implementing Async tasks with Kotlin
We will start coding. Here, I have used the following simple API to retrieve android version details.
  1. I have included a Button and TextView in my layout (activity_main.xml) file. Here, Button and TextView is used to call the API and display the result from the API
    <?xml version="1.0" encoding="utf-8"?>  
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
        xmlns:app="http://schemas.android.com/apk/res-auto"  
        xmlns:tools="http://schemas.android.com/tools"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        tools:context=".MainActivity"  
        tools:layout_editor_absoluteX="0dp"  
        tools:layout_editor_absoluteY="81dp">  
      
        <TextView  
            android:id="@+id/my_text"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_marginEnd="8dp"  
            android:layout_marginStart="8dp"  
            android:layout_marginTop="72dp"  
            android:text="AsyncTask Example"  
            android:textSize="18sp"  
            android:textStyle="bold"  
            app:layout_constraintEnd_toEndOf="parent"  
            app:layout_constraintStart_toStartOf="parent"  
            app:layout_constraintTop_toTopOf="parent" />  
      
        <ProgressBar  
            android:id="@+id/MyprogressBar"  
            style="?android:attr/progressBarStyle"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_marginEnd="8dp"  
            android:layout_marginStart="8dp"  
            android:layout_marginTop="32dp"  
            android:visibility="invisible"  
            app:layout_constraintEnd_toEndOf="parent"  
            app:layout_constraintStart_toStartOf="parent"  
            app:layout_constraintTop_toBottomOf="@+id/my_text" />  
      
        <Button  
            android:id="@+id/CallBtn"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_marginEnd="8dp"  
            android:layout_marginStart="8dp"  
            android:layout_marginTop="36dp"  
            android:text="Execute AsyncTask"  
            app:layout_constraintEnd_toEndOf="parent"  
            app:layout_constraintStart_toStartOf="parent"  
            app:layout_constraintTop_toBottomOf="@+id/MyprogressBar" />  
      
    </android.support.constraint.ConstraintLayout>
Then open your Activity file (in my case MainActivity.kt) and create a class with AsynTask as a parent.
AsyncTask has three main methods.
  1. onPreExecute – State before task performance
  2. doInBackground – State for task performance
  3. onPostExecute – State after task performance
Add the following code with your AsyncTask class. Here I have used
HttpURLConnection” to access the API Link.
BufferedReader” to read the response output of the API Link.
JSONObject” to parse the response from server.
Async Task Class can be called in the following method.
AsyncTaskExample(this).execute()
Full Code of MainActivity:
You can find the full code implementation of MainActivty.kt in the following
class MainActivity : AppCompatActivity() {

    private val tag: String = "MainActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        CallBtn.setOnClickListener {
            AsyncTaskExample(this).execute()
        }
    }

    @SuppressLint("StaticFieldLeak")
    class AsyncTaskExample(private var activity: MainActivity?) : AsyncTask() {

        override fun onPreExecute() {
            super.onPreExecute()
            activity?.MyprogressBar?.visibility = View.VISIBLE
        }

        override fun doInBackground(vararg p0: String?): String {

            var result = ""
            try {
                val url = URL("http://demosmushtaq.16mb.com/api/post_sample.php?version_index=14")
                val httpURLConnection = url.openConnection() as HttpURLConnection

                httpURLConnection.readTimeout = 8000
                httpURLConnection.connectTimeout = 8000
                httpURLConnection.doOutput = true
                httpURLConnection.connect()

                val responseCode: Int = httpURLConnection.responseCode
                Log.d(activity?.tag, "responseCode - " + responseCode)

                if (responseCode == 200) {
                    val tempStream: InputStream = httpURLConnection.inputStream
                    result = convertToString(tempStream)
                }
            } catch (ex: Exception) {
                Log.d("", "Error in doInBackground " + ex.message)
            }
            return result
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            activity?.MyprogressBar?.visibility = View.INVISIBLE
            if (result == "") {
                activity?.my_text?.text = activity?.getString(R.string.network_error)
            } else {
                var parsedResult = ""
                var jsonObject: JSONObject? = JSONObject(result)
                jsonObject = jsonObject?.getJSONObject("data")
                parsedResult += "Code Name : " + (jsonObject?.get("code_name")) + "\n"
                parsedResult += "Version Number : " + (jsonObject?.get("version_number")) + "\n"
                parsedResult += "API Level : " + (jsonObject?.get("api_level"))
                activity?.my_text?.text = parsedResult
            }
        }

        private fun convertToString(inStream: InputStream): String {

            var result = ""
            val isReader = InputStreamReader(inStream)
            val bReader = BufferedReader(isReader)
            var tempStr: String?

            try {

                while (true) {
                    tempStr = bReader.readLine()
                    if (tempStr == null) {
                        break
                    }
                    result += tempStr
                }
            } catch (Ex: Exception) {
                Log.e(activity?.tag, "Error in convertToString " + Ex.printStackTrace())
            }
            return result
        }
    }
}

Download Code

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub.

Figure 1 Introduction  In this article, we will learn how to create layout reveal animation in Android. This feature is available by...

Circular Reveal Animation In Android Circular Reveal Animation In Android

A blog about android developement

Figure 1

Introduction 

In this article, we will learn how to create layout reveal animation in Android. This feature is available by default from Lollipop. For pre-Lollipop Android versions, an awesome library is available and it is very easy to use.

Circular Reveal animations can be found in WhatsApp while clicking attachment option. It’s more interactive to users. We will learn in detail how to use in Lollipop and Pre-Lollipop devices separately.

Circular Reveal Animation

We already know this feature is available from Lollipop devices. To perform the same features in pre-Lollipop devices we will go for a third party library and it’s awesome to use.

Steps

I have divided this Implementation into 4 steps as shown in the following.
Step 1 - Creating New Project with Android Studio
Step 2 - Setting up the library for the project.
Step 3 - Implementation of Circular Reveal for Pre-Lollipop devices.
Step 4 - Implementation of Circular Reveal for Lollipop devices.

Step 1: Creating New Project with Android Studio

  1. Open Android Studio and Select create a new project.
  2. Name the project as per your wish and select an Empty activity.
    Android
    Figure 5
  3. Click finish button to create a new project in Android Studio.

Step 2 - Setting up the library for the project

  1. Open App Level gradle file and add the following lines to add the Libraries.
    dependencies {  
        ...  
        implementation 'com.android.support:appcompat-v7:26.1.0'  
        implementation 'com.android.support:support-annotations:27.1.1'  
        implementation 'com.android.support.constraint:constraint-layout:1.1.2'  
        implementation 'com.android.support:design:26.1.0'  
      
        // Third Party Library  
        implementation 'com.github.ozodrukh:CircularReveal:1.1.0'  
        ...  
    }  
      
    repositories {  
        maven {  
            url "https://jitpack.io"  
        }  
    }
  2. Then click “Sync Now” to add the library.

Step 3 - Implementation of Circular Reveal for Pre-Lollipop devices

  1. Open your designer file that is your XML layout file (In my case, I have opened my xml file) and paste the following code below toolbar if you want.
    <io.codetail.widget.RevealFrameLayout  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"> 
      
        <LinearLayout  
            android:id="@+id/reveal_items"  
            android:layout_width="match_parent"  
            android:layout_height="match_parent"  
            android:background="@android:color/white"  
            android:orientation="horizontal"  
            android:gravity="center"  
            android:padding="16dp"> 
      
            <LinearLayout  
                android:layout_width="match_parent"  
                android:layout_height="wrap_content"  
                android:orientation="horizontal"> 
      
                <ImageView  
                    android:layout_gravity="center"  
                    android:id="@+id/imageView"  
                    android:layout_width="wrap_content"  
                    android:layout_height="wrap_content"  
                    android:background="@drawable/ic_search_green" /> 
      
                <EditText  
                    android:id="@+id/search_box"  
                    android:layout_width="match_parent"  
                    android:layout_height="wrap_content"  
                    android:hint="Search Here..."  
                    android:inputType="text"  
                    android:imeOptions="actionSearch"  
                    android:maxLines="1"/> 
            </LinearLayout> 
        </LinearLayout> 
      
    </io.codetail.widget.RevealFrameLayout>
  2. Here, Reveal Frame Layout itself is used to handle Reveal animation. The Reveal effect can be applied to the whole screen.
  3. We have initialized the immediate child of the RevealFrameLayout and by default its state should be GONE or INVISIBLE. While changing its View states, the RevealFrameLayout will clips its child’s shape
    revealLayout = findViewById(R.id.reveal_items);  
    revealLayout.setVisibility(View.INVISIBLE);
  4. To perform the animation, import SupportAnimator class from the third party library included for Pre-Lollipop devices.
    import io.codetail.animation.SupportAnimator;  
    import io.codetail.animation.ViewAnimationUtils;
  5. Then add the following to perform the animation in forth and reverse. We need X, Y co-ordinates to perform the animation.
    SupportAnimator animator = ViewAnimationUtils.createCircularReveal(layout, cx, cy, 0, radius);  
    animator.setInterpolator(new AccelerateDecelerateInterpolator());  
    animator.setDuration(800);  
      
    SupportAnimator animator_reverse = animator.reverse();  
      
    if (hidden) {  
        layout.setVisibility(View.VISIBLE);  
        animator.start();  
        invalidateOptionsMenu();  
        hidden = false;  
    } else {  
        animator_reverse.addListener(new SupportAnimator.AnimatorListener() {  
            @Override  
            public void onAnimationStart() {  
      
            }  
      
            @Override  
            public void onAnimationEnd() {  
                layout.setVisibility(View.INVISIBLE);  
                invalidateOptionsMenu();  
                hidden = true;  
            }  
      
            @Override  
            public void onAnimationCancel() {  
      
            }  
      
            @Override  
            public void onAnimationRepeat() {  
      
            }  
        });  
        animator_reverse.start();  
    }
  6. Here,
    cx - co-ordinate in X axis.
    cy – co-ordinate in Y axis.
    These two are required for starting the animation in X, Y axis of the screen. It can be calculated by the following code.
    int cx = revealLayout.getRight();  
    int cy = revealLayout.getTop();
    radius - can be calculated by the following code.
    int radius = Math.max(layout.getWidth(), layout.getHeight());
    Animation can be started by SupportAnimator and it is assigned to another SupportAnimator which is used to start the reverse animation. So, the reverse animation will be handled by itself.
    SupportAnimator animator = ViewAnimationUtils.createCircularReveal(layout, cx, cy, 0, radius);  
    animator.setInterpolator(new AccelerateDecelerateInterpolator());  
    animator.setDuration(800);  
      
    SupportAnimator animator_reverse = animator.reverse();  
      
    if (hidden) {  
        layout.setVisibility(View.VISIBLE);  
        animator.start();  
        invalidateOptionsMenu();  
        hidden = false;  
    } else {  
        animator_reverse.addListener(new SupportAnimator.AnimatorListener() {  
            @Override  
            public void onAnimationStart() {  
      
            }  
      
            @Override  
            public void onAnimationEnd() {  
                layout.setVisibility(View.INVISIBLE);  
                invalidateOptionsMenu();  
                hidden = true;  
            }  
      
            @Override  
            public void onAnimationCancel() {  
      
            }  
      
            @Override  
            public void onAnimationRepeat() {  
      
            }  
        });  
        animator_reverse.start();  
    }
    hidden – is a Boolean value used to know the View State.
  7. Probably this does not seem to work from Lollipop devices. So we have to go for a different method which is shown in the next step.

Step 4 - Implementation of Circular Reveal for Lollipop devices

  1. No 5 in the previous step is slightly changed for Lollipop devices. Instead of “io.codetail.animation.ViewAnimationUtils”, use “android.view.ViewAnimationUtils”.
  2. No need to assign animation.reverse(). Instead of it, use the following.
    if (hidden) {  
        Animator anim = android.view.ViewAnimationUtils.createCircularReveal(layout, cx, cy, 0, radius);  
        layout.setVisibility(View.VISIBLE);  
        anim.start();  
        invalidateOptionsMenu();  
        hidden = false;  
      
    } else {  
    Animator anim = android.view.ViewAnimationUtils.createCircularReveal(layout, cx, cy, radius, 0);  
        anim.addListener(new AnimatorListenerAdapter() {  
            @Override  
            public void onAnimationEnd(Animator animation) {  
                super.onAnimationEnd(animation);  
                layout.setVisibility(View.INVISIBLE);  
                hidden = true;  
                invalidateOptionsMenu();  
            }  
        });  
        anim.start();  
    }
  3. To reverse the animation, the radius value is interchanged. The animation is handled from toolbar menu options.

Full Code

You can find the full code implementation here.
public class MainActivity extends AppCompatActivity {  
  
    Toolbar toolbar;  
    LinearLayout revealLayout;  
    EditText searchBox;  
    boolean hidden = true;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  
        toolbar = findViewById(R.id.toolbar);  
        setSupportActionBar(toolbar);  
  
        revealLayout = findViewById(R.id.reveal_items);  
        revealLayout.setVisibility(View.INVISIBLE);  
        searchBox = findViewById(R.id.search_box);  
        searchBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {  
            @Override  
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {  
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {  
                    handleKeyboard(searchBox);  
                    searchBox.clearFocus();  
                    Toast.makeText(MainActivity.this, textView.getText().toString(), Toast.LENGTH_SHORT).show();  
                    return true;  
                }  
                return false;  
            }  
        });  
    }  
  
    void handleKeyboard(View view) {  
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
        assert inputManager != null;  
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);  
    }  
  
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        getMenuInflater().inflate(R.menu.menu_reveal, menu);  
        if (hidden) {  
            menu.findItem(R.id.action_search).setIcon(R.drawable.ic_search);  
        } else {  
            menu.findItem(R.id.action_search).setIcon(R.drawable.ic_close);  
        }  
        return true;  
  
    }  
  
    @Override  
    public boolean onOptionsItemSelected(MenuItem item) {  
        switch (item.getItemId()) {  
            case R.id.action_search:  
                int cx = revealLayout.getRight();  
                int cy = revealLayout.getTop();  
                makeEffect(revealLayout, cx, cy);  
                searchBox.setText(null);  
                return true;  
            case android.R.id.home:  
                supportFinishAfterTransition();  
                return true;  
        }  
  
        return super.onOptionsItemSelected(item);  
    }  
  
    private void makeEffect(final LinearLayout layout, int cx, int cy) {  
  
        int radius = Math.max(layout.getWidth(), layout.getHeight());  
  
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {  
  
            SupportAnimator animator = ViewAnimationUtils.createCircularReveal(layout, cx, cy, 0, radius);  
            animator.setInterpolator(new AccelerateDecelerateInterpolator());  
            animator.setDuration(800);  
  
            SupportAnimator animator_reverse = animator.reverse();  
  
            if (hidden) {  
                layout.setVisibility(View.VISIBLE);  
                animator.start();  
                invalidateOptionsMenu();  
                hidden = false;  
            } else {  
                animator_reverse.addListener(new SupportAnimator.AnimatorListener() {  
                    @Override  
                    public void onAnimationStart() {  
  
                    }  
  
                    @Override  
                    public void onAnimationEnd() {  
                        layout.setVisibility(View.INVISIBLE);  
                        invalidateOptionsMenu();  
                        hidden = true;  
                    }  
  
                    @Override  
                    public void onAnimationCancel() {  
  
                    }  
  
                    @Override  
                    public void onAnimationRepeat() {  
  
                    }  
                });  
                animator_reverse.start();  
            }  
        } else {  
            if (hidden) {  
                Animator anim = android.view.ViewAnimationUtils.createCircularReveal(layout, cx, cy, 0, radius);  
                layout.setVisibility(View.VISIBLE);  
                anim.start();  
                invalidateOptionsMenu();  
                hidden = false;  
  
            } else {  
                Animator anim = android.view.ViewAnimationUtils.createCircularReveal(layout, cx, cy, radius, 0);  
                anim.addListener(new AnimatorListenerAdapter() {  
                    @Override  
                    public void onAnimationEnd(Animator animation) {  
                        super.onAnimationEnd(animation);  
                        layout.setVisibility(View.INVISIBLE);  
                        hidden = true;  
                        invalidateOptionsMenu();  
                    }  
                });  
                anim.start();  
            }  
        }  
    }  
}

Output Demo

You can find the output of this example.

Download Code

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub.