Custom Button with Shadow Duolingo style Android Button

custom button with shadow

In this blog learn to create Duolingo Style Custom Button with Shadow in Android.

custom button with shadow

Duolingo is a great app (available for both Android and iOS) for language learners across the world. With more than a million active users using the app daily, there is a lot we can learn from its simple yet elegant UI design.

To get started, here is a blog on how we can create Duolingo Style Button with Shadow.

Custom Button with Shadow

In your, Android Studio Project go to res > drawable.

Right-click and click on ‘New’ > ‘Drawable Resource File’

Name the file as ‘custom_button.xml’

Now, add the following lines of XML code:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Bottom 15dp Shadow -->
    <item>
        <shape  android:shape="rectangle">

<!--            Button Shadow Color -->
            <solid android:color="#52772C" />
            <corners android:radius="7dp" />

        </shape>
    </item>

    <!-- White Top color -->
    <item android:bottom="15px">

        <shape  android:shape="rectangle">
            <padding android:bottom="10dp"
                android:top="10dp"
                android:left="20dp"
                android:right="20dp"/>

<!--            Button TOP Color -->
            <solid android:color="#7CB342" />
            <corners android:radius="7dp" />
        </shape>

    </item>


</layer-list>
custom button with shadow
Duolingo style button with shadow

Now go to Activity or fragment and create a button.

To this button add a background attribute as:

android:background="@drawable/custom_button"

Your complete code for the button should look as follows:

 <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Duolingo Style"
        android:layout_above="@+id/btn_2"
        android:layout_margin="20dp"
        android:textColor="@android:color/white"
        android:background="@drawable/custom_button"/>

We hope you liked this blog, explore more about creating a custom button in Android Studio here.

Android Image Button with Text Example | Java & Kotlin

android image button with text

Android Image Button with Text Example in both Java and Kotlin. In this blog learn how to create an Image Button with text in Android Studio using XML code.

Though we have a widget in Android Studio known as Android ImageButton, but an ImageButton can’t have an image and a text together.

So if you’re building an app where you want to show the user the image and text both on a button, there is a smarter way to achieve the result as shown below using a RelativeLayout in Android.

android image button with text
Android Image Button with Text

Understanding Image Button Layout

To create a custom image button with a text we will create a relative layout with a custom background. Inside the relative layout, there will be an ImageView and a textView widget.

Creating a custom background for Button

We will first start with crating a custom background for our image button. Here is the XML code to create custom background.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" >
        <shape android:shape="rectangle"  >
            <corners android:radius="3dip" />
            <stroke android:width="1dip" android:color="#5e7974" />
            <gradient android:angle="-90" android:startColor="@color/colorAccent" android:endColor="@color/colorAccent"  />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="rectangle"  >
            <corners android:radius="3dp" />
            <stroke android:width="1dip" android:color="#5e7974" />
            <solid android:color="#58857e"/>
        </shape>
    </item>
    <item >
        <shape android:shape="rectangle"  >
            <corners android:radius="7dip" />
            <stroke android:width="0dip" android:color="#5e7974" />
            <gradient android:angle="-90" android:startColor="@color/colorAccent" android:endColor="@color/colorAccent"  />
        </shape>
    </item>
</selector>

To know more about Custom Backgrounds in android click here.

Android Image Button (XML Code)

Now lets code the android image button with textView inside it.

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

    <RelativeLayout
        android:id="@+id/image_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="@drawable/round_btn"
        tools:layout_editor_absoluteX="9dp"
        tools:layout_editor_absoluteY="26dp">

        <ImageView
            android:layout_margin="10dp"
            android:id="@+id/image"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/ic_computer_black_24dp"/>

        <TextView
            android:layout_centerVertical="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@+id/image"
            android:layout_margin="10dp"
            android:fontFamily="sans-serif-smallcaps"
            android:textStyle="bold"
            android:paddingStart="20dp"
            android:paddingEnd="20dp"
            android:text="Connect to Laptop"
            android:textAllCaps="false"
            android:textColor="#FFF"
            android:textSize="20sp" />

    </RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

As you can interpret from the code above, we have used an android relative layout inside which we have an ImageView and a TextView both together formaing an Image Button for our project.

Custom Image Button Java Code

Here is an OnClickListener Java Code for our custom image button

package com.aaveti.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        RelativeLayout compBtn = findViewById(R.id.image_btn);
        compBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showToast("I am an Image Button");
            }
        });

    }

    void showToast(String msg){
        Toast.makeText(MainActivity.this,"The day of the week is " + msg,Toast.LENGTH_LONG).show();
    }
}

Custom Image Button Kotlin Code

Here is an OnClickListener Kotlin Code for our custom image button

package com.aaveti.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        RelativeLayout compBtn = findViewById(R.id.image_btn);
        compBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showToast("I am an Image Button");
            }
        });

    }

    void showToast(String msg){
        Toast.makeText(MainActivity.this,"The day of the week is " + msg,Toast.LENGTH_LONG).show();
    }
}

TaDa! That’s all. You’re done with creating your own Custom Image Button for your Android Project.

However, if you want to add a custom more styling like a gradient effect to your image button, view here.

Is Relative Layout something new to you or you want to refresh your knowledge about it? You can View some of our more detailed tutorial with illustrations about Relative Layout here.

Android Button Animation Top 8 Styles you can apply in Android Studio

android button animation

Android Button Animation is a great way to provide a better user experience to your app users. In this blog learn about different types of animation styles you can apply to your Android buttons widget.

android button animation
android button animation

Android Button Animation

Getting Started

To get started with this tutorial from scratch you can create an empty android studio activity else you can skip this step and proceed further if you are already working on some Android Studio project and want to learn about Android button animation.

Creating Layout file

In an empty layout file, create a simple android button widget. Code for the following is as follow:

<?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">

    <Button
        android:id="@+id/hello_world"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Coding the Android Button Animation

Now first create the Button object in your java class and lets code their animation below:

Transparency Effect (Alpha)

To get the transparency effect in your android buttons like shown in the Medium app above, we play with alpha values of our buttons.

First set the alpha value of your button to zero and then animate the alpha value to 1.0f to get complete 100% opacity. Note here you can change the curation of the animation as well by using the setDuration function. See the code below:

        //findviewbyID
        Button helloWorld = findViewById(R.id.hello_world);

        //Set button alpha to zero
        helloWorld.setAlpha(0f);
        
        //Animate the alpha value to 1f and set duration as 1.5 secs.
        helloWorld.animate().alpha(1f).setDuration(1500);

Move the button (Translation)

To move your button like we have shown in the Medium example app above, we use the translation property i.e., transationX and translationY.

Android Button Animation
Android Button Animation

To achieve an animation like the Medium app buttons, we will first use setTranslationY to change position of our button on the Y asix and then animate its position to previous location by using translationByY.

        helloWorld = findViewById(R.id.hello_world);

        helloWorld.setAlpha(0f);
        helloWorld.setTranslationY(50);
        
        helloWorld.animate().alpha(1f).translationYBy(-50).setDuration(1500);

translationX vs translationXBy

While coding you may have noticed that there are two different properties of translation for both X and Y i.e., translationX vs translationXBy.

translationX is used to animate the Android button to that particular point on the activity where as translationXBy animates the Android Button by the amount mentioned.

Rotate the Button

If you wish to rotate the button you can easily do this by using the rotation property rotation();

helloWorld = findViewById(R.id.hello_world);
helloWorld.animate().rotation(120).setDuration(3000);

Rotate on Axis

If you want to rotate the button on axis i.e, on X axis or on the Y axis, you can achieve the same by using rotationX or rotationY.

helloWorld = findViewById(R.id.hello_world);
helloWorld.animate().rotationX(120).setDuration(3000);

Scale the Button

If you wish to scale your button then you can use scaleXBy or scaleYBy property. Here is an example for the same:

helloWorld = findViewById(R.id.hello_world);
helloWorld.animate().scaleYBy(1).setDuration(3000);

Set Delay

You can easily set Delay using the setStartDelay function.

helloWorld = findViewById(R.id.hello_world);
helloWorld.setAlpha(0f);
helloWorld.setTranslationY(50);
       helloWorld.animate().alpha(1f).translationYBy(-50).setStartDelay(200).setDuration(1500);

Set Actions

One can easily set the start or the end actions after animation starts or gets finished by using withStartAction or with EndAction methods.

//End Action

helloWorld.animate().alpha(1f).translationYBy(-50).setStartDelay(200).withEndAction(new Runnable() {
            @Override
            public void run() {
                //End Action
                Toast.makeText(MainActivity.this,"Animating Button",Toast.LENGTH_SHORT).show();
            }
        }).setDuration(1500);

TaDa Viola! So here we are done with learning 8 different animation actions you apply to your Android Button Animation.

To learn more about designing a button See here: Android Button Design, 6 different styles!.

How to get Android Custom Button Shape?

Android Custom Button Shape
Android Custom Button Shape

If you’re someone who would like to create your own android custom button shape and style, here is way you can do. We’ve created a custom button shape and shared its tutorial below!

To achieve this, you’ll have to first create a new android drawable resource file.

To create this file, in ‘Android’ section of Project Panel on the left, go to app > res > drawable

Right click on ‘drawable’ folder and select ‘New > Drawable Resource File’

Create a new file named ’rounded_rectangle’

In this new file write the following line of code:

<?xml version="1.0" encoding="utf-8"?>

<shape android:shape="rectangle"

    xmlns:android="http://schemas.android.com/apk/res/android">

    <!--Radius of all four corners-->
    <corners
        android:bottomRightRadius="50dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="50dp"
        android:topRightRadius="10dp"/>

            <!--Stroke size and color-->
            <stroke android:width="3dp"
                android:color="@color/colorAccent" />

            <!--Fill Color of the Button-->
            <gradient android:angle="-90"
                android:startColor="#000000"
                android:endColor="#000000"  />
        </shape>

Once done, go back to your main xml file which contains the button and add following attribute to it:

android:background="@drawable/rounded_rectangle"

To achieve what we have got in the image above, add following lines of code:

   <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="56dp"
        android:textColor="@color/colorAccent"
        android:textSize="17sp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:paddingStart="25dp"
        android:paddingEnd="25dp"
        android:focusable="true"
        android:textAllCaps="false"
        android:background="@drawable/rounded_btn"
        android:text="View Reports"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

Note:

  • In case you would like to change the button color, you’ll have to change the android:startColor=”#00000000″ and android:endColor=”#00000000″ attribute in rounded_rectangle.xml file.
  • In case you would like to change the stroke size, you’ll have to change the android:width=”3dp” attribute.
  • To change the shape of button you’ll have to change the following attributes!
<corners
android:bottomRightRadius="50dp"
android:bottomLeftRadius="10dp"
android:topLeftRadius="50dp"
android:topRightRadius="10dp"/>

Interested in adding more customization to your button? See here Android Button Design, 6 new Style!

Android Button Design, 6 New Styles!

android imageview

Android Button Design Blog is written keeping in mind Material Design guidelines.

Button Widget in an Android App plays a very important role in user interaction. It prompts user to interact with the app and brings more meaning to app design.

Here are 6 different android XML files that you can use as reference for android button design in your app.

1. Android Button Basic Design

We have used Android constraint layout in the following example.

Android Button Design
Android Button Design

To achieve this basic design style, write following lines of code:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="56dp"
        android:textColor="@color/white"
        android:textSize="17sp"
        android:padding="20dp"
        android:textAllCaps="false"
        android:backgroundTint="@color/colorAccent"
        android:text="View Reports"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

2. Android Button Rounded Rectangle Design

Android Button Design
Android Button Design

To achieve a rounded rectangle design as shown above, you’ve to first create a new android drawable resource file.

To create this file, in ‘Android’ section of Project Panel on the left, go to app > res > drawable

Right click on ‘drawable’ folder and select ‘New > Drawable Resource File’

Create a new file named ’rounded_rectangle’

In this new file write the following line of code:

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="10dp">

    <solid android:color="@color/colorAccent"/> <!-- this one is the color of the Rounded Button -->

    <corners
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>

</shape>

Once done, go back to your main xml file which contains the button and add following attribute to it:

android:background="@drawable/rounded_rectangle"

To achieve what we have got in the image above, add following lines of code:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="56dp"
        android:textColor="@color/white"
        android:textSize="17sp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:paddingStart="25dp"
        android:paddingEnd="25dp"
        android:focusable="true"
        android:textAllCaps="false"
        android:background="@drawable/rounded_btn"
        android:text="View Reports"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

Note: In case you would like to change the button color, you’ll have to change the shape color attribute in rounded_rectangle.xml file or add android:backgroundTint attribute to ‘Button’ widget!

3. Rounded Design

Android Button Design
Android Button Design

Rounded Design looks quite good. In order to achieve this style you’ll have to first create a new android drawable resource file.

To create this file, in ‘Android’ section of Project Panel on the left, go to app > res > drawable

Right click on ‘drawable’ folder and select ‘New > Drawable Resource File’

Create a new file named ’rounded_rectangle’

In this new file write the following line of code:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners android:radius="50dp"/> // if you want clear round shape then make radius size is half of your  button`s height.

    <solid android:color="@color/colorAccent"/> // Button Colour
    <padding
        android:bottom="10dp"
        android:left="25dp"
        android:right="25dp"
        android:top="10dp"/>

</shape>

Once done, go back to your main xml file which contains the button and add following attribute to it:

android:background="@drawable/rounded_rectangle"

To achieve what we have got in the image above, add following lines of code:

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="56dp"
        android:textColor="@color/white"
        android:textSize="17sp"
        android:focusable="true"
        android:textAllCaps="false"
        android:background="@drawable/rounded_btn"
        android:text="View Reports"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

Note: In case you would like to change the button color, you’ll have to change the shape color attribute in rounded_rectangle.xml file or add android:backgroundTint attribute to ‘Button’ widget!

4. On Press Change Color

Android Button Design
Android Button Design

If you like to add more colors to your Android Button Design, you can add state_focused and state_pressed to your Android Button widgets and change color of your button whenever user presses the button.

To achieve this, you’ll have to first create a new android drawable resource file.

To create this file, in ‘Android’ section of Project Panel on the left, go to app > res > drawable

Right click on ‘drawable’ folder and select ‘New > Drawable Resource File’

Create a new file named ’rounded_rectangle’

In this new file write the following line of code:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true" >
        <shape android:shape="rectangle"  >

            <corners android:radius="12dp" />

            <stroke android:width="1dp"
                android:color="#E91E63" />

            <gradient android:angle="-90"
                android:startColor="#E91E63"
                android:endColor="#F44336"  />
        </shape>
    </item>

    <item android:state_focused="true">
        <shape android:shape="rectangle"  >

            <corners android:radius="12dip" />

            <stroke android:width="1dip"
                android:color="#F44336" />

            <solid android:color="@color/colorAccent"/>

        </shape>
    </item>

    <item >
        <shape android:shape="rectangle"  >

            <corners android:radius="12dp" />

            <stroke android:width="5dp"
                android:color="#FF9800" />

            <gradient android:angle="-90"
                android:startColor="#FF9800"
                android:endColor="#FFC107" />

        </shape>
    </item>

</selector>

Once done, go back to your main xml file which contains the button and add following attribute to it:

android:background="@drawable/rounded_rectangle"

To achieve what we have got in the image above, add following lines of code:

   <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="56dp"
        android:textColor="@color/white"
        android:textSize="17sp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:paddingStart="25dp"
        android:paddingEnd="25dp"
        android:focusable="true"
        android:textAllCaps="false"
        android:background="@drawable/rounded_btn"
        android:text="View Reports"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

Note: In case you would like to change the button color, you’ll have to change the shape color attribute in rounded_rectangle.xml file.

5. Empty Button Design

Android Button Design
Android Button Design

One of our favorite, the empty button design style. As shown above, in this button design xml file we have added radius to make button rounded and filled it with the transparent color (” #00000000 “) !

To achieve this, you’ll have to first create a new android drawable resource file.

To create this file, in ‘Android’ section of Project Panel on the left, go to app > res > drawable

Right click on ‘drawable’ folder and select ‘New > Drawable Resource File’

Create a new file named ’rounded_rectangle’

In this new file write the following line of code:

<?xml version="1.0" encoding="utf-8"?>

<shape android:shape="rectangle"

    xmlns:android="http://schemas.android.com/apk/res/android">

            <corners android:radius="50dp" />

            <stroke android:width="3dp"
                android:color="@color/colorAccent" />

            <gradient android:angle="-90"
                android:startColor="#00000000"
                android:endColor="#00000000"  />
        </shape>

Once done, go back to your main xml file which contains the button and add following attribute to it:

android:background="@drawable/rounded_rectangle"

To achieve what we have got in the image above, add following lines of code:

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="56dp"
        android:textColor="@color/colorAccent"
        android:textSize="17sp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:paddingStart="25dp"
        android:paddingEnd="25dp"
        android:focusable="true"
        android:textAllCaps="false"
        android:background="@drawable/rounded_btn"
        android:text="View Reports"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

Note: In case you would like to change the button color, you’ll have to change the shape color attribute in rounded_rectangle.xml file.

6. Custom Button Design

If you’re someone who would like to create your own custom design and style, here is way you can do. We’ve created a custom shape and shared its tutorial below!

To achieve this, you’ll have to first create a new android drawable resource file.

To create this file, in ‘Android’ section of Project Panel on the left, go to app > res > drawable

Right click on ‘drawable’ folder and select ‘New > Drawable Resource File’

Create a new file named ’rounded_rectangle’

In this new file write the following line of code:

<?xml version="1.0" encoding="utf-8"?>

<shape android:shape="rectangle"

    xmlns:android="http://schemas.android.com/apk/res/android">

    <!--Radius of all four corners-->
    <corners
        android:bottomRightRadius="50dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="50dp"
        android:topRightRadius="10dp"/>

            <!--Stroke size and color-->
            <stroke android:width="3dp"
                android:color="@color/colorAccent" />

            <!--Fill Color of the Button-->
            <gradient android:angle="-90"
                android:startColor="#00000000"
                android:endColor="#00000000"  />
        </shape>

Once done, go back to your main xml file which contains the button and add following attribute to it:

android:background="@drawable/rounded_rectangle"

To achieve what we have got in the image above, add following lines of code:

   <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="56dp"
        android:textColor="@color/colorAccent"
        android:textSize="17sp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:paddingStart="25dp"
        android:paddingEnd="25dp"
        android:focusable="true"
        android:textAllCaps="false"
        android:background="@drawable/rounded_btn"
        android:text="View Reports"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

Note:

  • In case you would like to change the button color, you’ll have to change the android:startColor=”#00000000″ and android:endColor=”#00000000″ attribute in rounded_rectangle.xml file.
  • In case you would like to change the stroke size, you’ll have to change the android:width=”3dp” attribute.
  • To change the shape of button you’ll have to change the following attributes!
<corners
android:bottomRightRadius="50dp"
android:bottomLeftRadius="10dp"
android:topLeftRadius="50dp"
android:topRightRadius="10dp"/>

Interested in adding more customization to your button? See here Android Material Loading Button

Android Material Loading Button

Material Loading Button

A configurable and animated material loading button. If you’re an RxJava fan as I am this button will come you really handy.

material loading button

Usage

Minimum SDK: 21

Currently this widget is running with androidX and also allows the usage of databinding to set the elements comfortably.

Gradle

allprojects {
  repositories {
    maven { url 'https://jitpack.io' }
  }
}
dependencies {
 implementation 'com.github.Muki1992:MaterialLoadingButton:1.0'
 }

Indicating the loading progress

fun doStuff(view: View) {
    loadingButton.onStartLoading()
    Handler().postDelayed({
    loadingButton.onStopLoading()
    }, 500)
}

XML

<de.mustafagercek.library.LoadingButton      
   android:id="@+id/loading_button"      
   android:layout_width="match_parent"      
   android:layout_height="wrap_content"      
   app:buttonText="Do stuff"         
   app:onButtonClick="@{(view)->presenter.doStuff(view)}"               
   bind:buttonColor="@{@color/colorPrimary}"/>

Accessing attributes programatically

All custom attributes can be set like below:

loadingButton.setButtonOnClickListener(View.OnClickListener)

loadingButton.setButtonColor(Int)

loadingButton.setTextColor(Int)

loadingButton.setButtonText(String)

License

Copyright 2019 Mustafa Gercek

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Also See: Android Custom Button

Learn to use Translate Animation in Android

translate animation in android

Translate animation in Android is useful in moving widgets along X and Y axis. The animation is essentially some last-minute instructions to the screen composition engine to offset the view by x/y, rotate by z

translate animation in android
Translate animation in Android

To use the translate animation, we can use the <translate> tag in android’s anim xml resource file. We will show the example later, but first lets learn more about the <translate> tag attributes.

The <translate> Tag

The translate tag has the following attributes that helps it in showcasing the translate animation in android.

android:fromXDelta | android:fromYDelta

The fromXDelta or fromYDelta attribute is used to determine the starting point of the translate animation. Its value is in percentage where 0% means the animation will start from the x,y coordinate where its located.

android:toXDelta | android:toYDelta

The toXDelta or toYDelta is used to determine till which point the animation will take place. Its value is also in percentage of the height of the view you are animating.

android:duration

The duration attribute in the translate is used to determine the duration till which the animation will be playing. The number is in milliseconds, so 1000ms is 1 second.

android:repeatCount

As the name suggests, the repeatCount attribute is used to determine how many times the animation must be played. You can this number to infinite in case you want the animation to loop forever till the view is Visible on the screen.

android:repeatMode

The repeatMode attribute is used to determine that once the animation has played completely from point A to B in suppose 1000ms, then should it play in reverse mode from point B to point A or play from point A again in case the repeatCount is infinite.

Hands on Practical

Now that we have learned about all important attributes of the translate animation in android, its time to put it inn practice and run it using Android Studio.

Learn more about animating views in android here!

Getting Started

Create a new project file in Android Studio.

Creating animation file

Click on the Project panel on the Left. Search for the ‘res‘ folder. Right click on the res folder. Go to New >> Android Resource Directory.

You will see a popup dialog as shown above. Name the Directory name as ‘anim’ and Resource type as ‘anim’. Click OK.

Now you’ll notice an anim folder inside the res folder has been created.

Right click on the anim folder and go to New >> Android Anim Resource File.

A new popup window will open and here name the xml file as ‘translate.xml’.

Now as we have explain above about the <translate> tag and its attributes, we will be using it to create our animation.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate
        android:fromXDelta="0%"
        android:toXDelta="50%"
        android:duration="500"
        android:repeatMode="reverse"
        android:repeatCount="infinite"/>
</set>

In the code above, the view will move from 0 percent to 50 percent in 500 milliseconds. The view will repeat infinite and once the animation is complete it will move back from point B to point A again because we have set the repeatMode as reverse.

The Layout File

For this example we have used a Relative layout and inside it we have used a button widget which is centered in the parent. The XML code for the same is as follows:

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".ButtonTranslateAnimation">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Demo Button"
        android:layout_centerInParent="true"
        android:id="@+id/translate_button"/>

</RelativeLayout>

Code it in Kotlin

Now lets move to MainActivity.kt file and code up our animation and attach it to the respective view.

package com.example.androiddvlpr

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.Button

class ButtonTranslateAnimation : AppCompatActivity() {

    private lateinit var button : Button
    private lateinit var anim : Animation

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

        button = findViewById(R.id.translate_button)
        anim = nimationUtils.loadAnimation(this,R.anim.translate_animation)
        button.startAnimation(anim)

    }
}

In the code above we have created a Button and an Animation object. Next we’ve used the startAnimation(anim_res) method inside which we have passed the Animation resource file.

TaDa! Build and run your code and you will notice that the button is moving horizontally infinitely.

Table Layout in Android explained in 3 Steps

table layout in android

A Table layout in Android arranges the children’s layout inside it in rows and columns. Its like Nesting the Linear Layout in Android but without taxing the resources.

What is a Table Layout ?

The Table layout’s tag <TableLayout> consists of the Table Row tag <TableRow> objects that defines the row of the table layout. Inside the table row <TableRow> tag you can have other <View> children ex: TextView, Buttons, ImageView, etc.

table layout in android
A table layout in android XML with 1 Row and 3 columns

The Table layout class extends the Linear Layout class and it’s recommended to use Table Layout in your XML file, instead of nesting Linear layouts (i.e, one layout inside another) wherever appropriate.

Each row inside the table layout, the <TableRow> can have zero i.e, null or more views to hold.

The number of column in the table layout determined by the row with most views.

To create a Table layout in Android Studio using XML we use the <TableLayout> Tag. Inside it we use the <TableRow> tag to create rows. The Table Row tag <TableRow> can contain view elements what has to be aligned horizontally.

Table Layout Attributes

Table Layout contains the following attributes:

android:id

Just like any other Android widget, the id attribute is used to uniquely identify the layout.

attributes of table layout in android

android:shrinkColumns

Use this attribute to tell Android what columns can shrink. The columns start from index 0. So if you want the 1st and the 4th column to collapse, we use android:collapseColumns:”0,4″. Shrink the column will shrink the column to its minimum space required.

android:stretchColumns

Use this attribute to tell Android what columns can stretch. The columns start from index 0. SO if you want the 1st and the 5th column to stretch, we use android:collapseColumns:”0,5″.

android:collapseColumns

Use this attribute to tell Android what columns can collapse. The columns start from index 0. So if you want the 1st and the 5th column to collapse, we use android:collapseColumns:”0,5″. Collapse Column will hide the column.

Android Table Layout Demo App

Create a new Android Studio project with an empty activity.

Table Layout using XML Layout

In the XML file, create a <TableLayout> Tag. To the Table layout tag, add the following attributes:

<TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:stretchColumns="0"
        android:shrinkColumns="2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

</TableLayout>

Now add a <TableRow> tag and to this add layout_width and layout_height attribute.

 <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

 </TableRow>

Inside the Table Row tag, add as may views you want. We have added two widgets.

 <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_margin="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="This column is"
                android:textSize="22sp"/>

            <TextView
                android:layout_margin="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="And I am"
                android:textSize="22sp"/>

 </TableRow>

Once you’ve closed the </TableRow> tag, you can add another row to the table layout by opening a new <TableRow> Tag and adding new views to it.

<TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Button
                android:layout_margin="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="STRETCHeDDDDDDDDDD"/>

            <Button
                android:layout_margin="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Normalll"/>

            <Button
                android:layout_margin="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Shrinked"/>

</TableRow>

You can find the complete source code here:

<?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="match_parent"
    tools:context=".MainActivity">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:stretchColumns="0"
        android:shrinkColumns="2">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_margin="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="This column is"
                android:textSize="22sp"/>

            <TextView
                android:layout_margin="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="And I am"
                android:textSize="22sp"/>

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Button
                android:layout_margin="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="STRETCHeDDDDDDDDDD"/>

            <Button
                android:layout_margin="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Normalll"/>

            <Button
                android:layout_margin="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Shrinked"/>

        </TableRow>

    </TableLayout>
    
</LinearLayout>

Table Layout using Kotlin / Java Code

        //set 2nd column collapse-able
        tableLayout.setColumnCollapsed(1,true)

        //check if 2nd column is collapse-able
        tableLayout.isColumnCollapsed(1)

        //set 1st column shrinkable
        tableLayout.setColumnShrinkable(0,true)

        //check if 1st column is shrinkable
        tableLayout.isColumnShrinkable(0)

        //set 3rd column Stretchable
        tableLayout.setColumnStretchable(2,true)

        //check if 3rd column is Stretchable
        tableLayout.isColumnStretchable(2)

See TableLayout Source Code

Zxing Android Example | In 5 minutes Build QR Code Scanner App

Zxing Android library is a great Android QR Scanner code library that you can use to build an Android QR code scanning app. In this tutorial, we will teach you how to do the same in Java and Kotlin Programming language.

What is a QR Code?

A QR Code is 2 dimensional Bar code which was initially designed in 1994 for the automobile industry in Japan. It’s an optical coded label that can be decrypted and read by machines.

Generating your own QR Code

You can start this example by creating your own QR Code. Visit this website here and insert a sample text or url.

The QR Code will automatically get generated that you can scan later after building the app.

Zxing Android Library

To build an android app for scanning QR Codes we will be using Android Library which is based on Zxing QR code scanning android library.

We will also need to declare the CAMERA permission in Android manifest to access the device camera.

Once the user opens the app, the app will request the permission, if not granted and then scan the QR Code automatically and the decoded result text will appear as a Toast message.

You can alternatively, use the text message and make it appear in a SnackBar or TextView.

The source code files are available in the end for download .

Creating QR Code Scanner App

Creating Android Project

Open Android Studio and create a new project in Java or Kotlin (your preference, we have provided source code for both).

The Code Scanner Library supports both programming languages.

Implementing the dependency

Implement the following Code Scanner Dependency in build.gradle app level.

    implementation 'com.budiyev.android:code-scanner:2.1.0'

Creating the Layout XML File

In the activity_main.xml or where ever you want to create the code scanner, add the following line of XML code.

Code scanner layout using zxing android library
Code scanner layout using zxing android library
    <com.budiyev.android.codescanner.CodeScannerView
        android:id="@+id/scanner_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:autoFocusButtonColor="@android:color/white"
        app:autoFocusButtonVisible="true"
        app:flashButtonColor="@android:color/white"
        app:flashButtonVisible="true"
        app:frameColor="@android:color/white"
        app:frameCornersSize="50dp"
        app:frameCornersRadius="0dp"
        app:frameAspectRatioWidth="1"
        app:frameAspectRatioHeight="1"
        app:frameSize="0.75"
        app:frameThickness="2dp"
        app:maskColor="#77000000"/>

In the code above, we have created the CodeScannerView widget. In the widget, we have set following attributes:

  • Focus button color
  • Flash Button Color
  • Frame to highlight the QR code boundary
  • Frame border
  • Mask

Declaring the required Permission

Declare the access to device Camera in AndroidManifest.xml

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

Building the QR Scanner (Java)

Requesting and Checking if permission Granted

Using ContextCompact, we will first check if the user has been granted the app, the required permission to access the device camera. If not then we will the user a prompt message.

// the code below appears in onCreate() method 
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_DENIED){
            ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.CAMERA}, 123);
        } else {
           startScanning();
        }

Once the permission is granted, we have to call startScanning() method again.

 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 123) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Camera permission granted", Toast.LENGTH_LONG).show();
                startScanning();
            } else {
                Toast.makeText(this, "Camera permission denied", Toast.LENGTH_LONG).show();
            }
        }
    }

Coding the Code Scanner

In the startScanning() method we will create the CodeScanner (private Variable) and CodeScannerView.

    private CodeScanner mCodeScanner;
private void startScanning() {
        CodeScannerView scannerView = findViewById(R.id.scanner_view);
        mCodeScanner = new CodeScanner(this, scannerView);
        mCodeScanner.setDecodeCallback(new DecodeCallback() {
            @Override
            public void onDecoded(@NonNull final Result result) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, result.getText(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        scannerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCodeScanner.startPreview();
            }
        });
    }

The CodeScanner has a setDecodeCallback method that will get the result. It gets activated when scannerView is clicked, so we have a setOnClickListener method for the same.

As we are using the device camera, so in order to save battery and device resources, we will also override the onPause and onResume method to manage the code scanner.

@Override
    protected void onResume() {
        super.onResume();
            if(mCodeScanner != null) {
                mCodeScanner.startPreview();
            }
    }

    @Override
    protected void onPause() {
        if(mCodeScanner != null) {
            mCodeScanner.releaseResources();
        }
        super.onPause();
    }

We’ve finally built the Code Scanner in Java using the zxing android library, You can build and run your app now.

The complete code for Java is here.

package com.androiddvlpr.zxingandroid;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.budiyev.android.codescanner.CodeScanner;
import com.budiyev.android.codescanner.CodeScannerView;
import com.budiyev.android.codescanner.DecodeCallback;
import com.google.zxing.Result;

public class MainActivity extends AppCompatActivity {

    private CodeScanner mCodeScanner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_DENIED){
            ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.CAMERA}, 123);
        } else {
           startScanning();
        }
    }

    private void startScanning() {
        CodeScannerView scannerView = findViewById(R.id.scanner_view);
        mCodeScanner = new CodeScanner(this, scannerView);
        mCodeScanner.setDecodeCallback(new DecodeCallback() {
            @Override
            public void onDecoded(@NonNull final Result result) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, result.getText(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        scannerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCodeScanner.startPreview();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 123) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Camera permission granted", Toast.LENGTH_LONG).show();
                startScanning();
            } else {
                Toast.makeText(this, "Camera permission denied", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
            if(mCodeScanner != null) {
                mCodeScanner.startPreview();
            }
    }

    @Override
    protected void onPause() {
        if(mCodeScanner != null) {
            mCodeScanner.releaseResources();
        }
        super.onPause();
    }
}

Also see: Android Best Practices from Experienced Developers | Top 18 Curated List

Building the QR Scanner (Kotlin)

Requesting and Checking if permission Granted

Using ContextCompact, we will first check if the user has been granted the app, the required permission to access the device camera. If not then we will the user a prompt message.

Insert the following lines of code in the onCreate() method:

 if (ContextCompat.checkSelfPermission(this@MainActivity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.CAMERA), 123)
        } else {
            startScanning()
        }

Also we will listen for user response if the permission was not granted earlier and prompt appears. The code for the same is as follows:

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 123) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Camera permission granted", Toast.LENGTH_LONG).show()
                startScanning()
            } else {
                Toast.makeText(this, "Camera permission denied", Toast.LENGTH_LONG).show()
            }
        }
    }

Coding the code scanner

In the startScanning() method we will create the CodeScanner (private Variable) and CodeScannerView.

 private lateinit var codeScanner: CodeScanner

    private fun startScanning() {
        // Parameters (default values)
        val scannerView: CodeScannerView = findViewById(R.id.scanner_view)
        codeScanner = CodeScanner(this, scannerView)
        codeScanner.camera = CodeScanner.CAMERA_BACK // or CAMERA_FRONT or specific camera id
        codeScanner.formats = CodeScanner.ALL_FORMATS // list of type BarcodeFormat,
        // ex. listOf(BarcodeFormat.QR_CODE)
        codeScanner.autoFocusMode = AutoFocusMode.SAFE // or CONTINUOUS
        codeScanner.scanMode = ScanMode.SINGLE // or CONTINUOUS or PREVIEW
        codeScanner.isAutoFocusEnabled = true // Whether to enable auto focus or not
        codeScanner.isFlashEnabled = false // Whether to enable flash or not

        // Callbacks
        codeScanner.decodeCallback = DecodeCallback {
            runOnUiThread {
                Toast.makeText(this, "Scan result: ${it.text}", Toast.LENGTH_LONG).show()
            }
        }
        codeScanner.errorCallback = ErrorCallback { // or ErrorCallback.SUPPRESS
            runOnUiThread {
                Toast.makeText(this, "Camera initialization error: ${it.message}",
                        Toast.LENGTH_LONG).show()
            }
        }

        scannerView.setOnClickListener {
            codeScanner.startPreview()
        }
    }

In Kotlin you can see we have set various attributes for our code scanner will are as follows:

        codeScanner.camera = CodeScanner.CAMERA_BACK // or CAMERA_FRONT or specific camera id
        codeScanner.formats = CodeScanner.ALL_FORMATS // list of type BarcodeFormat,
        // ex. listOf(BarcodeFormat.QR_CODE)
        codeScanner.autoFocusMode = AutoFocusMode.SAFE // or CONTINUOUS
        codeScanner.scanMode = ScanMode.SINGLE // or CONTINUOUS or PREVIEW
        codeScanner.isAutoFocusEnabled = true // Whether to enable auto focus or not
        codeScanner.isFlashEnabled = false // Whether to enable flash or not

Also there are two other callbacks for decoding and error handling.

In order to save the device battery and resources, We also need to override the onResume and the onPause method.

 override fun onResume() {
        super.onResume()
        if(::codeScanner.isInitialized) {
            codeScanner?.startPreview()
        }
    }

    override fun onPause() {
        if(::codeScanner.isInitialized) {
            codeScanner?.releaseResources()
        }
        super.onPause()
    }

TaDa! we have successfully built the QR Code scanner app using zxing android library.

The complete code for Kotlin is here:

package com.androiddvlpr.zxingandroidkotlin

import android.Manifest
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.widget.Toast
import com.budiyev.android.codescanner.*

class MainActivity : AppCompatActivity() {

    private lateinit var codeScanner: CodeScanner

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (ContextCompat.checkSelfPermission(this@MainActivity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.CAMERA), 123)
        } else {
            startScanning()
        }
    }

    private fun startScanning() {
        // Parameters (default values)
        val scannerView: CodeScannerView = findViewById(R.id.scanner_view)
        codeScanner = CodeScanner(this, scannerView)
        codeScanner.camera = CodeScanner.CAMERA_BACK // or CAMERA_FRONT or specific camera id
        codeScanner.formats = CodeScanner.ALL_FORMATS // list of type BarcodeFormat,
        // ex. listOf(BarcodeFormat.QR_CODE)
        codeScanner.autoFocusMode = AutoFocusMode.SAFE // or CONTINUOUS
        codeScanner.scanMode = ScanMode.SINGLE // or CONTINUOUS or PREVIEW
        codeScanner.isAutoFocusEnabled = true // Whether to enable auto focus or not
        codeScanner.isFlashEnabled = false // Whether to enable flash or not

        // Callbacks
        codeScanner.decodeCallback = DecodeCallback {
            runOnUiThread {
                Toast.makeText(this, "Scan result: ${it.text}", Toast.LENGTH_LONG).show()
            }
        }
        codeScanner.errorCallback = ErrorCallback { // or ErrorCallback.SUPPRESS
            runOnUiThread {
                Toast.makeText(this, "Camera initialization error: ${it.message}",
                        Toast.LENGTH_LONG).show()
            }
        }

        scannerView.setOnClickListener {
            codeScanner.startPreview()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 123) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Camera permission granted", Toast.LENGTH_LONG).show()
                startScanning()
            } else {
                Toast.makeText(this, "Camera permission denied", Toast.LENGTH_LONG).show()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if(::codeScanner.isInitialized) {
            codeScanner?.startPreview()
        }
    }

    override fun onPause() {
        if(::codeScanner.isInitialized) {
            codeScanner?.releaseResources()
        }
        super.onPause()
    }
}

Switch Case in Android Studio for Java and Kotlin

android switch case

Switch case in Android Studio can be used to create multiple possible outcomes for a given variable.

This variable can be a Primitive data type i.e, Integer, bit, short or char or even a String Class. But it can not be a boolean.

switch case in android
switch case flowchart

In the example below we will show you code for both Java and Kotlin Programming languages where we will be using the switch case statement in the Android Studio.

When to use Switch case in Android

Switch cases have certain limitations and before starting up with example we would like to discuss a few cases in which we can not use a switch statement.

  1. Boolean Input: Switch statements can not accept Boolean statements as input. It can only be a Primitive data type i.e, Integer, bit, short or char or even a String Class.
  2. Boolean Values: Unlike if-else statement where you calculate outcome on the basis of a possibility. Switch statements can be used for fixed data values. The cases inside the switch statement are fixed values and can’t be a boolean.
  3. Testing Expression: Switch statement can not be used to test expression. i.e, you can not have cases where case 20 > 5.

Example Code

In the following example, we will be using the switch statement to set the text of a textview widget basis of the int between 1 to 7 of the week.

To get started, create an xml file activity_main.xml with following line of code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:inputType="number"
        android:hint="Type a number from 1 to 7"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:text="Get Day of the week"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText" />

</androidx.constraintlayout.widget.ConstraintLayout>

Switch case in Java

To do a switch case in Java, here is the code:

package com.aaveti.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        final EditText editText = findViewById(R.id.editText);
        Button button = findViewById(R.id.btn);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String num;

                if(editText.getText() != null) {
                    num = editText.getText().toString();

                    switch (num){
                        case "1":
                            showToast("MONDAY");
                            break;
                        case "2":
                            showToast("TUESDAY");
                            break;
                        case "3":
                            showToast("WEDNESDAY");
                            break;
                        case "4":
                            showToast("THURSDAY");
                            break;
                        case "5":
                            showToast("FRIDAY");
                            break;
                        case "6":
                            showToast("SATURDAY");
                            break;
                        case "7":
                            showToast("SUNDAY");
                            break;
                        default:
                            showToast("---INVALID---");
                            break;
                    }
                }

            }
        });

    }

    void showToast(String msg){
        Toast.makeText(MainActivity.this,"The day of the week is " + msg,Toast.LENGTH_LONG).show();
    }
}

Switch or When case in Kotlin

To do a switch case in Kotlin, here is the code:

package com.aaveti.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast

class Main2Activity : AppCompatActivity() {

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

        val editText : EditText? = findViewById(R.id.editText)
        val button : Button? = findViewById(R.id.btn)

        button?.setOnClickListener {
            val num: String

            if (editText != null) {
                if (editText.text != null) {
                    num = editText.text.toString()

                    when (num) {
                        "1" -> showToast("MONDAY")
                        "2" -> showToast("TUESDAY")
                        "3" -> showToast("WEDNESDAY")
                        "4" -> showToast("THURSDAY")
                        "5" -> showToast("FRIDAY")
                        "6" -> showToast("SATURDAY")
                        "7" -> showToast("SUNDAY")
                        else -> showToast("---INVALID---")
                    }
                }
            }
        }

    }

    private fun showToast(msg: String) {
        Toast.makeText(this@Main2Activity, "The day of the week is $msg", Toast.LENGTH_LONG).show()
    }
}

The switch case is known as when in Kotlin. As you can see in the example above it is when(variable){ all possible cases }

TaDa, so here we are done with switch case example in Android. Do let me know in the comment section below if you faced any issues or need any further explaination.