Author

admin

Browsing

How To Reduce Android App Development Time Using Genymotion Free Emulator (For Personal Use) With Android Studio

genymotion free download virtual device

Not all of us can buy lots of real devices for testing.

That’s costly and time-wasting too. This is why emulators are born. It’s assured that emulators are far away from real devices in all aspects.

If you have experience with the Android default emulator, then you must know how frustrating that each moment we feel while testing our app.

So today I am going to talk about Genymotion. A free emulator – for personal use only. It has a paid version If you have any other plans.



So in this post, you will learn about

What is Genymotion?

Genymotion is a third party Android Emulator which helps developers to run and test apps. When compared to Android default emulators, It boots fast and quickly runs your app. It uses x86 architecture and make use of OpenGL hardware acceleration, that gives us a smooth operation.

genymotion free emulator download

Let’s learn, how to create an account on genymotion.com and download Genymotion.

How to create an account and download Genymotion?

Step 1

genymotion free emulator

Search “genymotion free” on Google or go to “https://www.genymotion.com/fun-zone/”

Step 2

 download genymotion free

Click on the button named “Download Genymotion Personal Edition”.

Step 3

genymotion create account

If you already have a Genymotion account, then you can sign in with your username and password. Otherwise, click on Create an account.

Step 4

how to install genymotion in windows

Fill up the form with valid details.

Step 5

6 genymotion tick create account

Tick the checkbox by agreeing on privacy policy, terms, and conditions. Now click on CREATE ACCOUNT button. Now Genymotion sends email to your registered email address.

Step 6

genymotion gmail user account activation

Go to your registered email account and click on the link like above.

Step 7

genymotion free emulator for personal use

Click on the link “Download Genymotion for personal use“.

Step 8

download genymotion free emulator

I recommend downloading genymotion with Virtual box. If the virtual box is already installed on your pc, then you can select the second option. If you are a Mac or Ubuntu user, scroll down to see the download links.
genymotion mac ubuntu windows 10

Then click on the download button based on the operating system.

Download Genymotion virtual devices

Step 9

genymotion installation

After downloading, Install Genymotion just like any other software in Windows. At last, launch Genymotion.
If you skip these step or you already installed Genymotion, then double click on the Genymotion icon and launch.

Step 10

download genymotion virtual device

When Genymotion launches, you can see a lot of virtual device templates. Select any one of them and click on the 3 vertical dot icon.

Step 11

genymotion free

Click “install” from the menu.

Step 12

genymotion android emulator download
You can configure the Genymotion virtual device here.

if you want the virtual keyboard tick on the checkbox Use virtual keyboard for text input, or you can use PC’s Keyboard. Click Install

Step 13

genymotion virtual device download starts

Download started.

Step 14

genymotion virtual device installed

After the download completion, click on the three vertical dot menu on the right side and click on start.

Step 15

genymotion virtual device started initialization

Genymotion virtual device started to load.

Step 16

genymotion free emulator virtual device

Genymotion has successfully installed on your PC.

Next section will discuss on Genymotion integration with Android Studio.

Download Genymotion plugin for Android Studio

Step 1

genymotion plugin android studio
Open Android Studio, go File->Settings

Step 2

genymotion plugin

1. Click on Plugins
2. Search Genymotion in search dialog box.
3. If genymotion not found, Click on Search repositories or Browse repositories.
3 and 4 are leading to same page.

Step 3

genymotion install plugin

Click the install button.

Step 4

restart android studio

Restart Android Studio for changes to take effect.

Step 5

restart dialog

Click on the restart button

Step 6

genymotion icon

After the restart, click on the genymotion icon.

Step 7

genymotion virtual device selection

Choose Virtual devices from the dialog box and click on Start

Step 8

android studio run dialog

Now click on the run button, genymotion virtual device will be shown on chooser dialog. Select and Click OK.

Step 9

genymotion android studio plugin
Done. Genymotion is successfully integrated with Android Studio. Now you can test all your application using the same steps.

How to install gapps or google play services on Genymotion

genymotion gapps install google play services

So many apps rely on google play services. Developers of Genymotion know that, So the latest version of Genymotion arrives with a widget named Open GAPPS. This widget simply installs play store in one click. Let me show you how to install play store on Genymotion.

Step 1

google play services for Genymotion

Genymotion provided with a GAPPS icon to install play store. Click on the icon.

Step 2

genymotion playstore gapps accept notice

Click Accept.

Step 3

download gapps or playstore in genymotion

Download starts.

Step 4

Genymotion gapps playstore restart now dialog

Click on Restart now, it will redirect to GApps website.

Step 5

how to install google play services on genymotion
That’s all, play store is successfully installed.

Step 6

install gapps google play services genymotion
Install your favorite apps and games now.

Why Android Studio not detecting Genymotion device

After the successful installation of Genymotion, I too have faced this problem. Do the below steps to solve

android studio not detecting genymotion device

Open genymotion software, on the top-left side, click on genymotion.

android studio not detecting genymotion device

Click on settings

android studio not detecting genymotion device

Click on ADB

android studio not detecting genymotion device

Select the radio button with the label “Use custom Android SDK Tools” , locate your Android SDK through BROWSE button, When the location reaches Android-SDK folder, select and open. If you have selected the proper SDK folder, then it turns out to say this folder is valid.

That’s all. Now Android Studio can launch Genymotion easily.

Conclusion
By reading this post, you already understood that Genymotion is far better than Android default emulator. It boots fast and runs your app in less time, it also provides lots of other features. Although, It lacks wearable support. For making a wear app, you must use Android default ones.
So all I want to say is just give it a try if you never have used Genymoion. Let us know your experience with Genymotion and if you enjoyed reading this article, consider sharing it on Facebook, Twitter, and Pinterest.

How To Move From One Activity To Another In Android

how to move from one activity to another in android
Do you want to know how to move from one Activity to Another in Android?

Okay…Let’s go.



How to start new Activity using Intent in Android

In Android, we can use Intent to start another activity. Intent can be used to launch other app activities too. But now we simply describe starting a new activity.



val intent = Intent(this@MainActivity, SecondActivity::class.java)
startActivity(intent)


this@MainActivity(MainActivity.this) – Here means Context, Activity is a subclass of Context.

That’s why we use this@MainActivity here. You can also use this, but assure that it’s a context.

SecondActivity::class.java(SecondActivity.this) – Name of Activity which you want to start.

Let’s dig more…

Two main parts here.

  • Intent(Context packageContext, Class cls) – Using this Intent’s constructor, we can create a way to our second activity.
  • startActivity(Intent intent) – It’s one of the methods in Activity class and launches activity specified in the Intent. If there is no Activity found, ActivityNotFoundException() gets called.

Intent needs a Java reference of class. That’s why We use here class.java part in Kotlin.

Create an Android Studio project

In this example, We just create two activities, when you click on the button, It shows Second Activity. Here I have used OnClickListener for click events, You can also use android:onClick”attribute.

Okay.

Open Android Studio and start a new Android Studio project.

Application name : Start New Activity Ex.

Company domain: androidride.com

Check to include Kotlin support.


Select minimum SDK:API 15 – Android 4.0.3 (Ice Cream Sandwich) and click Next.

Next dialog, Select Empty Activity and click Next.

Activity Name: MainActivity
Check Generate layout file

Layout Name: activity_main

Click Finish.

build.gradle(Project: StartNewActivityEx – Kotlin)



// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.2.71'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()    
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


build.gradle(Module:app)



apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.androidride.startnewactivityex"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}


colors.xml



<!--?xml version="1.0" encoding="utf-8"?-->
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>
</resources>


strings.xml



<resources>
    <string name="app_name">Start New Activity Ex</string>
</resources>


styles.xml



<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>


activity_main.xml



<!--?xml version="1.0" encoding="utf-8"?-->
 	<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center">

    <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="First Activity" android:textstyle="bold" android:textsize="45sp" android:layout_marginbottom="25dp">

    </textview></linearlayout>

MainActivity.kt



package com.androidride.startnewactivityex

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

    button.setOnClickListener{

        val intent = Intent(this@MainActivity,SecondActivity::class.java)
        startActivity(intent)

        }
    }
}



Create Second Activity

Right-click on App-> New -> Activity -> Empty Activity ->

Activity Name: SecondActivity

check Generate Layout File.

Layout Name: activity_second

Select your source language Kotlin/Java.

and click Finish.

activity_second.xml



<!--?xml version="1.0" encoding="utf-8"?-->
 	<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center">

    <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:textstyle="bold" android:textsize="45sp" android:text="Second Activity">

</textview></linearlayout>

SecondActivity.kt



package com.androidride.startnewactivityex

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class SecondActivity : AppCompatActivity()
{

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


    }
}

Run now.

launch new activity in android

This is so simple. Isn’t it?

If you found this article helpful. please share it.

Reference:

startActivity()

Intent class – google docs

4 Android TextView StrikeThrough XML & 2 Kotlin/Java Examples

Android TextView StrikeThrough XML

You might have seen strikethrough text in websites or apps.

Strikethrough used to show the old price or real price with the selling price.

It makes us think we get more discount, so it increases the chances to buy the product.

So If you are making an e-commerce app it’s better to know how to strikethrough a text.



Here, I have discussed 4 Android TextView StrikeThrough XML and 2 Java/Kotlin examples.


Then Let’s code.

1. Using Strike – Android TextView StrikeThrough XML example

Android TextView Strikethrough

Like Html, <Strike> tag easily creates a horizontal line through our TextView content. Create a string element in strings.xml and place text which you want to get strikethrough between <strike> opening tag and closing tag.

strings.xml


1. StrikeThrough Using strike




2. Using Paint Flags – TextView StrikeThrough Example

Android make TextView StrikeThrough

Paint class provides

STRIKE_THRU_TEXT_FLAG

named flag. It creates strikethrough for TextView easily.


        textview2.paintFlags = textview2.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        textview2.text = "2. StrikeThrough Using Paint Flags"

3.1 SpannableString – TextView StrikeThrough Example

android textview strikethrough

Applying StrikethroughSpan() with setSpan method of SpannableString, We can also create StrikeThrough.


val content1 = "3.1 StrikeThrough Using SpannableString"
        val spannableString1 = SpannableString(content1)
        spannableString1.setSpan(StrikethroughSpan(),0,content1.length,0)
        textview31.text = spannableString1

3.2 Using SpannableString – TextView StrikeThrough Example

We can control strikethrough where to appear in a text. For that, provide start and endpoints of the text. Here I StrikeThrough the content “StrikeThrough” using 4 as the start point and 17 as the endpoint.


val content2 = "3.2 StrikeThrough Using SpannableString"
        val spannableString2 = SpannableString(content2)
        spannableString2.setSpan(StrikethroughSpan(),4,17,0)
        textview32.text = spannableString2

4. Using shape drawable – Android TextView StrikeThrough XML

Android textview strikethrough color

Using Shape drawable, create a horizontal line and put that line middle of your text.

strikethrough_shape.xml




    
    


put strikethrough_shape.xml as TextView background attribute value.




5. Using LayerList – Android TextView StrikeThrough XML

android strikethrough textview

We can create a horizontal line using layerlist drawable also. Just like the above example, put this also as TextView’s background value.

strikethrough_layerlist




        
            
                
            
        



put strikethrough_layerlist.xml as TextView’s background value.




6. Using RelativeLayout and View – Android TextView Strikethrough XML example

Android textview strikethrough color

RelativeLayout positions its element relative to each other. So let’s create a horizontal line using view and position it above-center of the TextView.




        

        
    

How To Remove TextView StrikeThrough

Use inv() method with Paint.STRIKE_THRU_TEXT_FLAG. Java users, use this ‘~’ symbol with Paint.STRIKE_THRU_TEXT_FLAG. Just like below


textview.paintFlags = textview.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()

Create an Android Studio project

Let’s create a project with the above examples.

Open Android Studio and start a new Android Studio project.

Application name : TextView StrikeThrough Ex.

Company domain: androidride.example.com

Check to include Kotlin support.


Select minimum SDK:API 15 – Android 4.0.3 (Ice Cream Sandwich) and click Next.

Next dialog, Select Empty Activity and click Next.

Activity Name: MainActivity
Check Generate layout file

Layout Name: activity_main

Click Finish.

build.gradle(Project: TextViewStrikeThroughEx)

 

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.2.71'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

 

build.gradle(Module:App)

 

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.androidride.textviewstrikethroughex_kotlin"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

colors.xml




    #008577
    #00574B
    #D81B60


strings.xml



    TextView StrikeThrough Ex
    1. StrikeThrough Using strike


styles.xml




    
    



activity_main.xml




    

    

    

    

    

    

    

        

        
    



strikethrough_layerlist.xml



        
            
                
            
        


strikethrough_shape.xml




    
    


 

MainActivity.kt

 

package com.androidride.textviewstrikethroughex_kotlin

import android.graphics.Paint
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.SpannableString
import android.text.style.StrikethroughSpan
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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


        textview2.paintFlags = textview2.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        textview2.text = "2. StrikeThrough Using Paint Flags"

        val content1 = "3.1 StrikeThrough Using SpannableString"
        val spannableString1 = SpannableString(content1)
        spannableString1.setSpan(StrikethroughSpan(),0,content1.length,0)
        textview31.text = spannableString1

        val content2 = "3.2 StrikeThrough Using SpannableString"
        val spannableString2 = SpannableString(content2)
        spannableString2.setSpan(StrikethroughSpan(),4,17,0)
        textview32.text = spannableString2


    }
}

Let's run it.

Android TextView StrikeThrough XML

If you found this article helpful, please share it.

5 Amazing Ways To Underline A TextView In Android

underline a textview in android

Do you want to underline a TextView in Android?

In this post, you will learn how to underline a TextVew and also learn to change underline color.

You can download Java & Kotlin Source code too.



Okay, let’s get started.

1 – Underline a TextView in Android – Using Html.fromHtml()

underline a textview in android

It’s the simplest way. Html.fromHtml() method helps us to render HTML code in TextView.



val html = "<u>Underline using Html.fromHtml()</u>"
textview.text = Html.fromHtml(html)

But Html.fromHtml(resource : String) was deprecated in API 24. So now you can use HtmlCompat.fromHtml() method. It’s available in both android.support.v4.text.HtmlCompat, and androidx.core.text.HtmlCompat.

But androidx.core.text.HtmlCompat is the latest one. For that, you must include the dependency in gradle file.



implementation 'androidx.core:core:1.0.1'

underline a textview in android studio



val html = "<u> 1.1 Underline using HtmlCompat.fromHtml()</u>"
//1.1 underline textview using HtmlCompat.fromHtml() method
textview11.text = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY)

1.2 Above underline method in a direct way

underline below textview android

This is for beginners. You can directly implement the code just like below.



textview12.text = HtmlCompat.fromHtml("<u>1.2 Underline using HtmlCompat.fromHtml()</u> ", HtmlCompat.FROM_HTML_MODE_LEGACY)

1.3 – Underline TextView In Android Using String resource & HtmlCompat.fromHtml()

how to underline textview in android

In this method, we use strings.xml to store our HTML code and access using getString() method inside HtmlCompat.fromHtml() method.

The <u> tag doesn’t work with devices I checked. So I use < and; here. Just like below.

strings.xml



<string name="underline_text">1.3 <u>Underline using HtmlCompat.fromHtml() and string resource</u></string>



textview13.text = HtmlCompat.fromHtml(getString(R.string.underline_text), HtmlCompat.FROM_HTML_MODE_LEGACY)

2. Underline Using Paint Flags

android textview underline

You can use Paint flags to make underline below TextView. Use Paint.UNDERLINE_TEXT_FLAG.



        textview2.paintFlags = textview2.paintFlags or Paint.UNDERLINE_TEXT_FLAG
        textview2.text = "2. Underline using setPaintFlags()"

3.1 Underline using SpannableString

underline below textview android

You can underline TextView using SpannableString and setSpan() method with the help of UnderlineSpan().



val content1 = "3.1 Underline using SpannableString"
        val spannableString1 = SpannableString(content1)
        spannableString1.setSpan(UnderlineSpan(),0,content1.length,0)
        textview31.text = spannableString1

3.2 Underline Using SpannableString

how to underline textview in android

You can underline wherever you want in a word or sentence. Just Specify the start and endpoints.



val content2 = "3.2 Underline using SpannableString"
        val spannableString2 = SpannableString(content2)
        spannableString2.setSpan(UnderlineSpan(),4,13,0)
        textview32.text = spannableString2

Here 4 is the start point and 13 is the endpoint.

4. Underline Using Layerlist Drawable

android textview underline color

You can use XML drawable to make underline. Here I am going to talk about LayerList Drawable.

Make a drawable named underline_layerlist.xml, and paste below code.


<!--?xml version="1.0" encoding="utf-8"?-->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="-4dp" android:left="-4dp" android:right="-4dp">
        <shape android:shape="rectangle"><solid android:color="@android:color/transparent">
            <stroke android:width="1dp" android:color="#fa460a">
        </stroke></solid></shape>
    </item>
</layer-list>

Change Underline color using android:color attribute.

Here I used solid element color as transparent. If not, the solid element color becomes black in older devices (below Lolipop).

Change underline width using android:width attribute.

5. Underline using Shape Drawable

android textview underline color

Using Line shape we can create Underline below TextView Just like this.



<!--?xml version="1.0" encoding="utf-8"?-->
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="line">
    <padding android:bottom="15dp">
    <stroke android:width="1dp" android:color="#3737e5">
</stroke></padding></shape>

Here android:width and android:color are defines underline stroke and color just like layerlist drawable.

A Small Surprise – 6. Underline Using View element

android textview underline color

Here I just made a line using View element and place it below the TextView.



 	 	 	 	<linearlayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical">

        <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="6. Underline using View">

        <view android:layout_width="match_parent" android:layout_height="2dp" android:background="@color/colorPrimaryDark">
    </view></textview></linearlayout>


Create Android Studio Project – UnderlineTextView ex

Let’s create an Android Studio project with the above code examples.

Open your Android Studio,

Start a new Android Studio Project.

Application Name: UnderlineTextView Ex

Company domain: androidride.example.com

Check to include Kotlin support.


Select minimum SDK:API 15 – Android 4.0.3 (Ice Cream Sandwich) and click Next.

Next dialog, Select Empty Activity and click Next.

Activity Name: MainActivity
Check Generate layout file

Layout Name: activity_main

Click Finish.

copy paste below code in respective files.

build.gradle(Project: UnderlineTextView)


// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.2.71'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle(Module:app)


apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.androidride.underlinetextviewex_kotlin"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'androidx.core:core:1.0.1'
}

gradle.properties


# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1024m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
android.useAndroidX=true
android.enableJetifier=true


strings.xml


<resources>
    <string name="app_name">UnderlineTextView Ex</string>
    <string name="underline_text">1.3 <u>Underline using HtmlCompat.fromHtml() and string resource</u></string>
</resources>

activity_main.xml


<!--?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" android:orientation="vertical" android:gravity="center" tools:context=".MainActivity">

    <textview android:layout_marginbottom="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview11">

    <textview android:layout_marginbottom="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview12">

    <textview android:layout_marginbottom="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview13">

    <textview android:layout_marginbottom="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview2">

    <textview android:layout_marginbottom="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview31">

    <textview android:layout_marginbottom="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview32">

    <textview android:layout_marginbottom="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="4. Underline using layerlist drawable" android:background="@drawable/underline_layerlist">

    <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="5. Underline using shape drawable" android:background="@drawable/underline_shape">

     	 	 	 	<linearlayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical">

        <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="6. Underline using View">

        <view android:layout_width="match_parent" android:layout_height="2dp" android:background="@color/colorPrimaryDark">
    </view></textview></linearlayout>

</textview></textview></textview></textview></textview></textview></textview></textview></linearlayout>

underline_layerlist.xml


<!--?xml version="1.0" encoding="utf-8"?-->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="-4dp" android:left="-4dp" android:right="-4dp">
        <shape android:shape="rectangle"><solid android:color="@android:color/transparent">
            <stroke android:width="1dp" android:color="#fa460a">
        </stroke></solid></shape>
    </item>
</layer-list>

underline_shape.xml


<!--?xml version="1.0" encoding="utf-8"?-->
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="line">
    <padding android:bottom="15dp">
    <stroke android:width="1dp" android:color="#3737e5">
</stroke></padding></shape>

AndroidManifest.xml


<!--?xml version="1.0" encoding="utf-8"?-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidride.underlinetextviewex_kotlin">

    <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundicon="@mipmap/ic_launcher_round" android:supportsrtl="true" android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN">

                <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java


package com.androidride.underlinetextviewex_kotlin

import android.graphics.Paint
import android.os.Bundle
import android.text.SpannableString
import android.text.style.UnderlineSpan
import androidx.appcompat.app.AppCompatActivity
import androidx.core.text.HtmlCompat
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

            val html = "<u> 1.1 Underline using HtmlCompat.fromHtml()</u>"
            //1.1 underline textview using Html.fromHtml() method.
            textview11.text = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY)
            //1.2
            textview12.text = HtmlCompat.fromHtml("<u>1.2 Underline using HtmlCompat.fromHtml()</u> ", HtmlCompat.FROM_HTML_MODE_LEGACY)
            // 1.3 underline textview using Html.fromHtml() and string resource
            textview13.text = HtmlCompat.fromHtml(getString(R.string.underline_text), HtmlCompat.FROM_HTML_MODE_LEGACY)

        // 2 underline textview using setPaintFlags() method
        textview2.paintFlags = textview2.paintFlags or Paint.UNDERLINE_TEXT_FLAG
        textview2.text = "2. Underline using setPaintFlags()"

        // 3.1 - underline textview using spannablestring
        val content1 = "3.1 Underline using SpannableString"
        val spannableString1 = SpannableString(content1)
        spannableString1.setSpan(UnderlineSpan(),0,content1.length,0)
        textview31.text = spannableString1

        // 3.2 - underline any text in sentance, specifying start and end position of underline.
        val content2 = "3.2 Underline using SpannableString"
        val spannableString2 = SpannableString(content2)
        spannableString2.setSpan(UnderlineSpan(),4,13,0)
        textview32.text = spannableString2


    }
}


Okay. Let’s Run Now. You can use below links to Run your app.

underline a textview in android - android textview underline color

Yeah… That’s all for now.

Let me know if anything missing here.

Sharing is Caring.

3 Methods To Change Or Rename Android App Package Name in Android Studio

Sometimes, we make our app using the code from youtube tutorials and blogs and may forget to change the package name at the start. Yes, this happens, most of the time.

We don’t want to display other website name or Youtube channel name to be as our package name, We want a package name that defines us. If you are searching for a tutorial about how to change or rename the Android app package name in Android Studio, then this post is for you.



In this post, I am going to discuss 3 methods that I am using and still working.

Method I – How to rename android app package name in Android Studio

In this example, we will change package name com.androidride.myapplication” to “com.xyz.yourapplication”.

STEP 1

rename android app package name

  • Open Android Studio project, Select package name or Java, Click the gear icon.

STEP 2

rename android app package name

  • Deselect Hide Empty Middle Packages. This breaks your folder structure into parts.

rename android app package name

  • The package is brocken down.

STEP 3

rename android app package name

  • Right Click on AndroidRide, Refactor -> Rename . You can also use Shift + F6.

A warning will appear.

STEP 4

rename android app package name

  • Click on Rename package

STEP 5

rename android app package name

  • Clear AndroidRide and put new Name in it. Here “xyz”

    STEP 6

    rename android app package name

    • Click Do Refactor

    STEP 7

    rename android app package name

    • Repeat the same process.
    • Right click on myapplication,Refactor -> Rename and Rename package.

    STEP 8

    rename android app package name

    • Change myapplication to yourapplication

    STEP 9

    rename android app package name

    • Click on Do Refactor.

    STEP 10

    • After changing the package name, open build.gradle(module) and change Application Id

    STEP 11

    rename android app package name

    • change applicationid “com.androidride.myapplication” to “com.xyz.yourapplication”.
    • After changing applicationid, click on sync now.

    Congrats. Package name successfully changed.

    Method 2 – How to change full package name of project by creating new package

    In this method, We are going to change package name “com.androidride.myapplication” to “info.xyz.yourapplication”

    STEP 1

    android studio how to change package name

    • Right click on com.androidride.myapplication package and select Refactor->Move

    STEP 2

    android studio how to change package name

    • Choose Move package “com.androidride.myapplication” to another package and click on OK.

    STEP 3

    android studio how to change package name
    Now you will get a warning dialog shows Multiple directories correspond to package com.androidride.myapplication

    • Click on Yes

    STEP 4

    android studio how to change package name

    • Enter the new package name except the last level, For example. If you want to make package name as “info.xyz.yourapplication” then type “info.xyz” only, like above. Avoid the last part, here “yourapplication”.

      STEP 5

      android studio how to change package name

      • Click YES for creating new package.

      STEP 6

      android studio how to change package name

      • Click on Do Refactor. Now package name “com.androidride.myapplication” changes into “info.xyz.myapplication“.

      STEP 7

      android studio how to change package name

      Now we have to change the last package level name,

      • Right click on package name -> Refactor -> Rename

      STEP 8

      android studio how to change package name

      • Click on Rename package

      STEP 9

      android studio how to change package name

      • Rename “myapplication” in to “yourapplication”.

        STEP 10

        android studio how to change package name

        • Click on “Do Refactor”

        STEP 11

        android studio how to change package name

        • Use CTRL key and select each package related to old package name and delete. You can use DELETE key in keyboard or right click after selecting old packages and click on delete option from the menu.

        STEP 12

        android studio how to change package name

        • Open build.gradle file, change applicationId and Click on sync now.

        Package name successfully changed to “info.xyz.yourapplication“.

        Method III – How to rename android app package name in Android Studio using existing package

        This method is also same as the second method. Just like second, we change package name “com.androidride.myapplication” to “info.xyz.yourapplication“.

        STEP 1

        android studio change package name of project

        • Right click on Java and select New -> Package

          STEP 2

          change apk package name android studio

          • Next dialog box appears, choose …app\src\main\java as Destination Directory.

          STEP 3

          how to change package name android studio

          • Enter your package name, here info.xyz.yourapplication

          STEP 4

          android studio how to change package name

          • Now move old package files into new package. Here move files from “com.androidride.myapplication” to “info.xyz.yourapplication“. Just use CTRL key to select all files and drag it to new package.

          how to change full package name in android studio

          • Files moved.

          STEP 5

          rename android app package name

          • Open AndroidManifest.xml and change package name into “info.xyz.yourapplication

          .

          STEP 6

          android studio change package name

          • Open build.gradle (Module: app) file, change applicationId also. Change it to “info.xyz.yourapplication” and Click on Sync now.Now you might get errors. It is due to the R file import. There are two scenarios, we can do.
            1. Remove R file import line from both files and check the error still exists. If not then you can delete old package files now
            2. It’s done. You have successfully changed the package name.

            3. Otherwise, If the error still exists, do the below steps.
            4. STEP 7

              change package name android studio

              • Select R file import line just like above and press CTRL + SHIFT + R . Replace with new package name. Click on replace all.

              STEP 8

              android studio change package name of project

              • Click on replace

              STEP 9

              change apk package name android studio

              • Delete old package and related files

              STEP 10

              how to change package name android studio

              • Build->Rebuild

              Yes, the package name is changed.

              Express your thoughts below and tell your friends about this post. Thank you.
              how to change package name in android studio

2 Strategies about how to run android app over WiFi in Android Studio (without Root)

Having trouble with USB debugging???

Want to reduce the usage of USB??

In this post, we will show you two methods that help you to run the app over WiFi in Android Studio.

Really ??

Yes, this is simple, efficient and it will benefit you in the long run. If you are a beginner, we recommend you to take the strategy NO:1.

Are you curious to find out what it is ??

Go on…



Strategy NO:1 – Using Android WiFi ADB plugin
What will you need

  1. USB cable – initial setup
  2. Android Wifi ADB plugin

Open Android Studio,
how to run app over wifi in android studio adb wifi 1search-plugins

  1. Click Shift key twice or search icon at the top – right side corner of the Android Studio
  2. Search “plugins
  3. Click on plugins item on the list

You can also get plugins window by File->Settings->Plugins

how to run apk over wifi in android studio

  • Now plugins window will appear, just click on “Browse repositories

how to run android app over wifi in android studio

  1. Search “Android Wifi ADB” plugin”
  2. Select “Android WiFi ADB” from plugins list”
  3. Install it.

how install Adb over wifi in android studio download-plugin

    • The plugin will be downloaded.

how to run apk over wifi in android studio 5 adb wifi

Click “Restart Android Studio“.

how to run apk over wifi in android studio adb wifi

  • Android Studio shows a notification Restart Android Studio to activate changes in plugins? Click “Yes
    • Make sure that USB debugging is fine and successfully connected with the USB cable.

how to install android app over wifi in android studio

  • After the restart, just click the Android WiFi ADB icon that besides the run button like above.how to debug android apk over wifi in Android Studio
    • Android Studio notifies with a message that your device is connected.
    • Disconnect your device, otherwise run dialog will show your device twice. one as USB device, other as WiFi device.

    how to run android apk over wifi in android studio

    • Click the run button and select your device in the run device dialog.

    how to install apk over wifi in android studio 10installing apk

    After selecting the device, it will continue to download through WiFi and install on your device.

    Strategy NO:2 – How to run your app over WiFi using ADB commands

    Sometimes, This method may difficult for you if you are a beginner. But we are just

    • connecting the device using the IP address
    • Install the app through ADB command.

    Open Android Studio,

    how to run apk over wifi in Android Studio terminal

    • Click your terminal on Android Studio, You can also use the command prompt.

    how to run apk over wifi in Android Studio adb command

    • Type “adb devices” and Press Enter key – List the devices which are connected to system.

    If your device is plugged with USB, then it will show it to you on the terminal.

    how to run apk over wifi in android studio - adb over wifi

    • Type “adb tcpip 5555” and Press Enter key.

    Now you can disconnect your device.

    how to find ip address of android device

    Find the IP address of your smart device. You can find it by Settings-> About Phone -> Status -> IP address.

    how to run apk over wifi in Android Studio - Adb over wifi 3tcp 3
    Now connect your device over wifi by running

    • adb connect <IP address of your Android Device>:5555

    that’s all. your Android device successfully connected with computer.

    how to debug apk over wifi in Android Studio - adb over wifi

    • Install apk – adb install “full location of apk”
    • adb install C:/app-debug.apk – here C:/app-debug.apk – full location of APK, I just placed the APK to C drive.

    It’s a nice technique, but we are not saying that to leave USB cables forever. It’s needed for initial setup. If your pc and Android device restart again, Then you need to use USB cables again for reidentify the device.

    Share your experiences with us and don’t forget to share.

    Thanks for scrolling…

Open Calendar on Button Click in Android Example – Kotlin & Java

In this example, you will learn how to open the calendar on button click in Android with an example. Here I use DatePickerDialog, not CalendarView. Beginners tend to use Calendar, that’s why I use that here.



Download Source Code Now


Let’s discuss in simple steps.

1. Create a button and make it listen for events.


button.setOnClickListener
{

}

2. Access current date.

//getting current day,month and year.
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
       

3. Initialize DatePickerDialog with the current date and show it. If you don’t and use 0 as day, month, and year. Then DatePickerDialog shows Feb month 1900.


val datePickerDialog = DatePickerDialog(this@MainActivity, DatePickerDialog.OnDateSetListener
        { view, year, monthOfYear, dayOfMonth ->

           
        }, year, month, day)

datePickerDialog.show()


4. Get day, month and year from DatePickerDialog onDateSet() method.
When you select a date in DatePickerDialog, onDateSet() method gives day, year in the as correct number specified in DatePickerDialog. But month value varies from 0 to 11. So just add 1 to month value to show the original month number.

Just like below.


edittext.setText("" + dayOfMonth + " - " + (monthOfYear+1) + " - " + year)

Create Project – Open Calendar on Button click in Android Example

Let’s create a project that sets the date in EditText. When you click on Button, DatePickerDialog shows up, When you select a date, it sets on EditText.

Start a new Android Studio project

Application name: Open Calendar on Button Click in Android Example.

Company domain: androidride.example.com

check to include Kotlin support.


Select minimum SDK: API 15 – Android 4.0.3 (Ice Cream Sandwich) and click Next.

Next dialog, Select Empty Activity and click Next.

Activity Name: MainActivity
Check Generate layout file

Layout Name: activity_main

Click Finish.


Make a layout using below code

Open calendar on button click in Android Example
Open calendar on button click in Android Example

colors.xml



    #008577
    #00574B
    #D81B60


strings.xml


    Open Calendar on Button Click in Android Example

styles.xml



    
    


activity_main.xml



    
    

MainActivity.kt

class MainActivity : AppCompatActivity()
{

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

        val calendar= Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)


        button.setOnClickListener{

            val datePickerDialog = DatePickerDialog(this@MainActivity, DatePickerDialog.OnDateSetListener
            { view, year, monthOfYear, dayOfMonth ->

                edittext.setText("" + dayOfMonth + " - " + (monthOfYear+1) + " - " + year)

            }, year, month, day)

            datePickerDialog.show()


        }

    }

open calendar on button click in android example
open calendar on button click in android example

Conclusion
There are many occasions when you need a date from the user. Date of birth in sign up process, Ticket reservation, and date of an upcoming event just like that. It may not be user-friendly If the user needs to type it down. Android provides views for that, so users can easily pick it up. So I think if you are making an app like that, this post might have helped you. If you like this tutorial, please share it.

Reference
DatePickerDialog – Android doc

4 Ways to make Android TextView Bold

In this tutorial, you’ll learn four ways to make an Android TextView bold. You can easily adapt the code and use it in your project as needed. Let’s get started!



Way 1 – make Android TextView bold using android:textStyle attribute

android:textStyle attribute is the first and one of the best way to make the text in TextView bold. just use “bold”.



If you want to use bold and italic. Use pipeline symbol “|” . just like this “bold|italic”.

Way 2 – make Android TextView bold using setTypeface() method

TextView has a method called setTypeface() which needs

  1. Typeface
  2. Int styleflag

In our case, leave Typeface as null, use styleflag Typeface.BOLD.

textview2.setTypeface(null,Typeface.BOLD);
textview2.text= "TEXTVIEW 2"


You can use Typeface.ITALIC for italic style.

Way 3 – make Android TextView bold using Html.fromHtml() method

The fromHtml() method returns displayable styled text from given Html string. Using this advantage, we can make our text in TextView bold.

val html = "This is TEXTVIEW 3"
textview3.text = Html.fromHtml(html)


Html.fromHtml(String source) was deprecated in API level 24. Use androidx.core.text.HtmlCompat instead. For using HtmlCompat, you need to include dependency in your project.

implementation 'androidx.core:core:1.0.1'

If you got Manifest merger failed error, then add below code in gradle.properties.

android.useAndroidX=true
android.enableJetifier=true

        val html = "This is TEXTVIEW 3"
        textview3.text = HtmlCompat.fromHtml(html,HtmlCompat.FROM_HTML_MODE_LEGACY)

HtmlCompat.FROM_HTML_MODE_LEGACY – It just adds two newline character between block level elements.

Way 4 – Make Android TextView Bold using separate style

In this example, we create a separate style resource and set it to our TextView. The advantage of this technique – you can use this style for many TextViews. Just specifying style attribute.

Step 1

Create a separate style resource named “boldStyle”, add “android:textStyle” as item and provide value “bold”.

   
 

Step 2

Set style to TextView using style attribute.




Let’s create an Android app with these examples. Open your Android Studio,

Step 1

Start a new Android Studio project

Application name: TextView Bold – Kotlin

Company domain: androidride.example.com

check to include Kotlin support.


Step 2

Select minimum SDK: API 15 – Android 4.0.3 (Ice Cream Sandwich) and click Next.

Next dialog, Select Empty Activity and click Next.

Activity Name: MainActivity
Check Generate layout file

Layout Name: activity_main

Click Finish.


build.gradle(Project: TextView Bold – Kotlin)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.2.71'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle(Module: app)

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.androidride.textviewbold_kotlin"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies
        {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'

    testImplementation 'junit:junit:4.12'
      implementation 'androidx.core:core:1.0.1'
        }

gradle.properties

# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1024m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
android.useAndroidX=true
android.enableJetifier=true


colors.xml



    #008577
    #00574B
    #D81B60

strings.xml


    TextView Bold Example


styles.xml



    
    

    



activity_main.xml


 	 	 	 	 	 	 	 	

    

    

    

    




MainActivity.kt

package com.example.androidride.textviewbold_kotlin

import android.graphics.Typeface
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.text.HtmlCompat
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

        //Make textview bold - programmatically
        textview2.setTypeface(null,Typeface.BOLD)
        textview2.text= "TEXTVIEW 2"

        //Using fromHtml() method
        val html = "This is TEXTVIEW 3"
        textview3.text = HtmlCompat.fromHtml(html,HtmlCompat.FROM_HTML_MODE_LEGACY)

    }


}

Run Now

android textview bold example - android set text bold
android textview bold

If you find anything useful, please share it.
Thank you.

How to convert Java class to Kotlin in Android Studio

In this post, you will learn how to convert Java class to Kotlin in Android Studio. Google announced Kotlin as an official language for Android Development. When comparing Java with Kotlin, It has lots of advantages. But I am not going to talk about its advantages here.

If you are from Java and want to step into Kotlin world, But don’t know how to write your code in Kotlin. Don’t worry, Kotlin plugin helps to convert Java code to Kotlin in Android Studio. Just type your code in Java then use below steps

This is not 100% perfect, the Best way is to learn Kotlin on your own. But for beginners, This will help a lot to move forward with Kotlin.

If you are using below Android Studio 3.0, You must install Kotlin plugin. Then only below steps work. So go to this tutorial and install Kotlin plugin in Android Studio. Otherwise, Just read on.



Open any project in Android Studio, Here I have opened the HelloWorld App.

convert java class to kotlin android studio

  • Choose Code-> Convert Java File to Kotlin File or you can also use keyboard shortcut Ctrl + ALT + Shift + K.
  • convert java class to kotlin android studio

  • Now plugin starts its job and your .java files will convert to .kt files in the src folder.
  • convert java class to kotlin android studio

  • You will get a notification says “Kotlin not configured”. Just click on Configure.
  • configure kotlin plugin in android studio project

  • If you don’t get the configure option, then you need to go

    Tools-> Kotlin -> Configure Kotlin in Project

  • convert java class to kotlin andorid studio

  • Select the latest Kotlin compiler and runtime version, and click OK.
  • how to convert java class to kotlin in android studio 2

    After gradle configuration,

    1. ext.kotlin_version stores Kotlin version and uses in various spots.
    2. Added a dependency for Kotlin plugin
    3. How to convert Java class to Kotlin in Android Studio

    4. Kotlin plugin added
    5. Kotlin standard library dependency added.
    • you don’t have to convert each java file one by one for a big project, you can convert the whole package using the above method.
    • The plugin also converts automatically if you paste java code into Kotlin file.

    JetBrains team does not stop making java to Kotlin offline tool, they also provide an online tool.

    Convert Java code to Kotlin – online.

    convert java code to kotlin online

    • Go to this URL “https://try.kotlinlang.org/” and click on “Convert from Java”
    • how to convert java class to kotlin online
      how to convert java class to kotlin online
    • Just paste your java code in the left section and click on “convert to Kotlin” shown on the bottom of the box. Now Kotlin code will appear on the right section.

    Conclusion

    Kotlin has become one of the fastest growing languages after Google has selected it as an official language for Android Development. Many of the business giants are also started making big projects in Kotlin. If you are a beginner in Kotlin and know how to code in Java. Don’t worry you can convert it to Kotlin using the Kotlin plugin. Android Studio makes the process more simple, so you can accomplish migration in a few seconds. For the beginning days, It assists you well to understand the basic structure of Kotlin. I assume this post might have helped you and If you like this post, please share it. Any other ways to convert, feel free to comment here.

9 Android WebView Example Tutorial In Kotlin & Java

Do you want to create a web browser using Android WebView?

Don’t worry;

I’ll help you make a simple one, as shown below.

webview android in example kotlin
Android WebView browser



Download Project Source Code – Kotlin & Java

In this post, you will learn more about WebView. Okay, let’s start…

What is Android WebView?

There may be occasions when you want to show a webpage to your users such as Terms and conditions, app manual or your website and so on.

In a traditional way, we can send users to an external web browser but there is no guarantee that users would come back. So that’s one of the main reasons Android introduced a widget named WebView.

As the name suggests it helps to show or view online and offline web pages in our app. It’s available in android.webkit package and has abilities in history management, zooming, javascript, and CSS rendering.

So you can load the webpage easily in your app,  webview will take care of it. It’s not a browser because it lacks navigational toolbar like features.

From the beginning to now, WebView has grown a lot. Let’s check how it implemented in Android.

WebView to Android System Webview – implementation history

WebView to Android System WebView -WebView implementation history
WebView to Android System WebView -WebView implementation history

WebView was added in API level 1. It renders web pages using Webkit engine, which behind Apple’s Safari browser. Actually, WebKit makes an environment or views for the webpage to display on the app.

In Android 4.4, For better performance, Google decided to change webview rendering from stock webview to google’s chromium or blink.

Lots of bugs and fixes through os update, that made long time vulnerable. So Android engineers innovated a separate Android System Webview app that can install and update through Google’s app market Play store with next release “Lolipop”.

That made easy fixes in less time.

In Android 7.0, there is no need to enable Android System Webview app, Chrome will take care of webview. if it is disabled or uninstalled already, the system will use android system webview.

If both of them get disabled, webview will use stock Webkit engine and take care of your valuable web pages.

How to add WebView to your layout?

Webview can easily be added to your layout as any other view. You can just drag and drop webview or write code for that just like below

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

You can use it as a root element or as a child element. While using as a root element don’t forget to add XML namespace.

How To Create WebView Programmatically In Android?

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebView

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
    
    //make a webview object
    val webview= WebView(this)
      //show it through setcontentview()method
    setContentView(webview)
        
    }
}

What is layout in Android?

For Kotlin users, I am using Android studio 3.1.2 and it uses Kotlin Android Extensions plugin by default.  So there is no need to call findviewByid and cast. just use the id of the widget and call the methods.

Make sure Android Studio has imported these lines

import kotlinx.android.synthetic.main.activity_main.*

Okay… Let’s start with our first example – Using the loadUrl() method.

Load Url – WebView Android Example In Kotlin & Java

android webview loadurl example
android webview loadurl example

We can easily load a webpage in webview using loadUrl() method. Just put your URL as a string, Before that, we must provide Internet permission in AndroidManifest.xml.


create a webview app in android with below code

package com.androidride.webviewloadurlex

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

        //loads androidride homepage to webview, webview: id of webview
        webview.loadUrl("https://www.androidride.com")
    }
}

https://youtu.be/uQngvrzzuDo

android system webview version
android system webview version

If you are testing webview code in devices which contains Android System WebView version below 43.0.2357.121 or below Lolipop. If anyone below happens

  1. server side redirect
  2. Click on links in WebView

Then it might lead to opening an external browser. To force open all links in WebView, we need to set WebViewClient.

webview.webViewClient = WebViewClient()

This is enough to open your links in webview. It internally calls, shouldOverrideUrlLoading() method and it returns false. False means redirect or clicking on a link opens in the same webview, True will abort the operation.

How to open link in the external browser using Android WebView

Sometimes You need to open your website links in webview and other links in external browsers. Then you can use the below sample code.

replace “www.example.com” with your site name.

 webview.webViewClient = object : WebViewClient()
        {

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean
            {
                if(Uri.parse(url).host=="www.example.com")
                {
                    return false
                }

                val intent= Intent(Intent.ACTION_VIEW,Uri.parse(url))
                startActivity(intent)
                return true

            }
}

But shouldOverrideUrlLoading (WebView view, String url) was deprecated in API level 24. So if you are planning to make an application for Nougat or above, then you can use

public boolean shouldOverrideUrlLoading (WebView view,WebResourceRequest request)

To open links in WebView in All devices use both shouldOverrideUrlLoading() methods just like

webview.webViewClient = object : WebViewClient()
       {
           override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean
           {
               if(Uri.parse(url).host=="www.example.com")
               {
                   return false
               }

               val intent= Intent(Intent.ACTION_VIEW,Uri.parse(url))
               startActivity(intent)
               return true

           }

           @RequiresApi(Build.VERSION_CODES.N)
           override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean
           {
           val url=request?.url.toString()

               if(Uri.parse(url).host=="www.example.com")
               {
                   return false
               }
               val intent= Intent(Intent.ACTION_VIEW,Uri.parse(url));
               startActivity(intent)
               return true

           }
       }

How To Play YouTube Video In WebView By Enabling JavaScript In Android

Let’s open youtube in our webview.

Use our first example, and replace URL in loadUrl with “https://www.youtube.com” and run.

webview.loadUrl("https://www.youtube.com");

You may see these type of actions:

  1. Youtube shows a progress bar loading.
  2. Bowser says Please enable JavaScript in your browser.

This is because of JavaScript. If you are a web developer, you already know the importance of javascript. If you don’t, Javascript is a client-side programming language, it helps us to provide validation, animations and popups and so on.

By default, Javascript is disabled on your browser. we can easily enable it by simple lines of code.

how to enable javascript in android webview
how to enable javascript in android webview
//enables javascript in webview
      webview.settings.javaScriptEnabled = true

Now you can start watching youtube videos in your webview.

Android WebView local file example

android webview local file example
android webview local file example

In this example, you will learn how to show a local HTML file in webview. We have already created a webpage for you. You can use that for a sample.


<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Android webview local file ex - androidride</title>
<style type="text/css">
h1
{
border:2px solid #707cff;
padding:5px;
color:#707cff;
margin-top:120px;
text-align:center;
background-color:white;
}
p
{
text-align:center;
}
body
{
background-color:#e0e0e0;
}
</style>
</head>
<body>
<h1>ANDROIDRIDE</h1>
<p>
This is a <strong>local html file</strong> loaded from <strong>assets</strong> folder
</p>
</body>
</html>

This is a local html file loaded from assets folder

Just make an assets folder in your project, Right click on app->New->Folder->Assets Folder. Now a dialog appears to change the location of assets folder. Leave it and Click Finish.

Place demo.html into assets folder and use below code

package com.example.androidride.webviewlocalfileex

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
//loads local html file
        webview.loadUrl("file:///android_asset/demo.html")

    }
}

loadUrl() uses

LoadUrl() is a broad method and it works with:

    1. http:// and https:// URLs.

Eg: webview.loadUrl(“https://www.androidride.com”)
Webview.loadUrl(“//www.androidride.com”)

    1. Local filesystem URLs.

Eg: webview.loadUrl(“file:///storage/sdcard/index.html”)

Don’t forget to add


In your AndroidManifest.xml.

    1. Application assets and resources URLs.

eg:Webview.loadUrl(“file:///android_asset/demo.html”)

In URL, use android_asset not android_assets, yes, there is no ‘s’ at the end.

webview.loadUrl(“file:///android_res/mipmap/ic_launcher”)
There is no need for the file extension, but it won’t be a problem if you add it.

    1. content://URLs pointing content provider.

ERR_UNKNOWN_URL_SCHEME in Android WebView – Fixed.

err_unknown_url_scheme in android webview fixed
err_unknown_url_scheme in android webview fixed

In this example, You will learn how to solve ERR_UNKNOWN_URL_SCHEME in Android WebView. This type of error happens when WebView deals with UNKNOWN URL SCHEME links. Before that learn some basics.

What is URL SHEME?

The URL scheme is something before the colon in the URL. actually, it’s the protocol describes how to access the resource.

Scheme://host:port?path
eg: https://www.androidride.com:80/webview.html

WebView knows how to deal with HTTP, HTTPS, and file Schemes, but they don’t know what to do when these type of schemes come. ‘tel:’, ‘sms:’, and ‘mailto:’ and others.

So we have to tell webview to how to deal with those schemes in shouldOverrideUrlLoading() method. In this example, we are going to use ‘tel:’, ‘sms:’, ‘mailto:’, and ‘geo:’ links. When you click on them, each link will get opened with appropriate apps installed on your Android device.

demo.html

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Error Unknown URL scheme fixed - androidride</title>
</head>
<body>
<a href='tel:99999999999'>Click here to call</a><br><br>
<a href='sms:99999999999'>Click here to message</a><br><br>
<a href='mailto:example@mail.com'>Click here to mail</a><br><br>
<a href='geo:51.5074,0.1278'>Click here to show location</a><br><br>
</body>
</html>
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.util.Log
import android.webkit.URLUtil
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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


        webview.webViewClient = MyWebViewClient()
        webview.loadUrl("file:///android_asset/demo.html")
    }

    inner class MyWebViewClient : WebViewClient()
    {
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean
        {
            if(URLUtil.isNetworkUrl(url))
            {
                return false
            }
                try
                {
                val shareIntent= Intent()
                shareIntent.action=Intent.ACTION_VIEW
                shareIntent.data= Uri.parse(url)
                startActivity(shareIntent)
                }
                catch(e: ActivityNotFoundException)
                {
Toast.makeText(this@MainActivity, "Appropriate app not found", Toast.LENGTH_LONG).show()
                    Log.e("AndroidRide",e.toString())
                }
            return true
        }
        @RequiresApi(Build.VERSION_CODES.N)
        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean
        {
            val url=request?.url.toString()
            if(URLUtil.isNetworkUrl(url))
            {
                return false
            }
            try
            {
                val shareIntent= Intent()
                shareIntent.action=Intent.ACTION_VIEW
                shareIntent.data= Uri.parse(url)
                startActivity(shareIntent)
            }
            catch(e: ActivityNotFoundException)
            {
Toast.makeText(this@MainActivity, "Appropriate app not found", Toast.LENGTH_LONG).show()
                Log.e("AndroidRide",e.toString())
            }
            return true

        }

    }
}

      • If it’s a network URL, WebView force the links to open in WebView,otherwise find a best option from Android System.

Create your webview app with the above code or you can download our example.

WebView loadData() example in Android

In this Android WebView example, we will show you how to render HTML code in Android WebView. It’s simple, Android API provides a method called loadData().

loadData() method needs 3 contents.

      1. String htmlData: This is our html content.
      2. String mimeType: here we use “text/html”.
      3. String encoding: most of the time, base64 or UTF-8.
      • It works with data,http and https schemes.
      • If you use other schemes, webview can’t access content due to javascript same origin policy.
      • You should use loadDataWithBaseURL(), if you want to use other schemes.
class MainActivity : AppCompatActivity()
{

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

        val html="




Hi, AndroidRide

" webview.loadData(html,"text/html","UTF-8") } }
webview loaddata example
webview loaddata example in android

WebView loadDataWithBaseURL() example in Android

In this example, you will learn how to work with loadDataWithBaseURL() example. When you want to fetch an image from the assets folder using loadData() method. JavaScript origin policy restricts the access to content.

loadDataWithBaseURL() avoids this problem by specifying BaseURL. Using the Base URL, system resolve relative URLs in HTML content.

loadDataWithBaseURL() needs

  1. String baseURL: This URL is used to resolve relatvie URLs.
  2. String data: Html content that you want to show.
  3. String mimeType: mimeType of HTML data
  4. String encoding: encoding of html data
  5. String historyURL: This URL loads when you navigate back in webview

In this example, I am going to use the same loadData() code but just want to add image ‘ic_launcher’ from the mipmap folder.

class MainActivity : AppCompatActivity()
{

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

        val html="




Hi,AndroidRide

" webview.loadDataWithBaseURL("file:///android_res/mipmap/",html,"text/html","UTF-8",null) } }
loaddatawithbaseurl example
android webview loaddatawithbaseurl example

Android WebView Download File example

android webview download file example
android webview download file example

In this android webview example, you will learn how to download a file using WebView and DownloadManager. Using DownloadManager, we can reduce code and leave the stress to DownloadManager. We also show AlertDialog for Download notification.

You can download the file using AsyncTask too.

Create a webview app project in Android Studio, Add below lines to AndroidManifest.xml



    

Use below code

package com.example.androidride.webviewdownloadfileex

import android.Manifest
import android.app.DownloadManager
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AlertDialog
import android.webkit.CookieManager
import android.webkit.URLUtil
import android.webkit.WebViewClient
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

        webview.loadUrl("https://www.google.com")
        webview.webViewClient = WebViewClient()

        webview.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
            //checking Runtime permissions
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            {
                if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    //Do this, if permission granted
                    downloadDialog(url, userAgent, contentDisposition, mimetype)

                } else {

                    //Do this, if there is no permission
                    ActivityCompat.requestPermissions(
                        this,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        1
                    )

                }
            } else {
                //Code for devices below API 23 or Marshmallow
                downloadDialog(url, userAgent, contentDisposition, mimetype)

            }
        }
    }

    fun downloadDialog(url:String,userAgent:String,contentDisposition:String,mimetype:String)
    {
        //getting file name from url
        val filename = URLUtil.guessFileName(url, contentDisposition, mimetype)
        //Alertdialog
        val builder = AlertDialog.Builder(this@MainActivity)
        //title for AlertDialog
        builder.setTitle("Download")
        //message of AlertDialog
        builder.setMessage("Do you want to save $filename")
        //if YES button clicks
        builder.setPositiveButton("Yes") { dialog, which ->
            //DownloadManager.Request created with url.
            val request = DownloadManager.Request(Uri.parse(url))
            //cookie
            val cookie = CookieManager.getInstance().getCookie(url)
            //Add cookie and User-Agent to request
            request.addRequestHeader("Cookie",cookie)
            request.addRequestHeader("User-Agent",userAgent)
            //file scanned by MediaScannar
            request.allowScanningByMediaScanner()
            //Download is visible and its progress, after completion too.
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            //DownloadManager created
            val downloadmanager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
            //Saving file in Download folder
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,filename)
            //download enqued
            downloadmanager.enqueue(request)
        }
        //If Cancel button clicks
        builder.setNegativeButton("Cancel")
        {dialog, which ->
            //cancel the dialog if Cancel clicks
            dialog.cancel()
        }

        val dialog:AlertDialog = builder.create()
        //alertdialog shows
        dialog.show()

    }
}


How To Run JavScript In Android WebView

how to run javascript in android webview
how to run javascript in android webview

I already said JavaScript has an important role in the web world. In Android, we can also make use of JavaScript by sending data to Javascript from Android and vice versa. But it also raises security issues too. If you are using any third-party code, make sure it’s not vulnerable to users security.

Android API provides a number of methods and classes to achieve a super web app. I have categorized them

JavaScript calling Kotlin/Java

      1. addJavascriptInterface()
      2. WebMessagePort – (6.0)

Kotlin/Java calling JavaScript

      1. loadUrl()
      2. evaluateJavascript() – (4.4)
      3. WebMessage – (6.0)

The numbers shown in the brackets means the starting API. We are not going to discuss WebMessagePort and WebMessage here. That will be updated later.

webview addJavascriptInterface example in android

webview addjavascriptinterface
webview addjavascriptinterface example in android

In this addJavascriptInterface example, we send a message from a local HTML webpage to Android and show it through a toast.

JavaScript can access methods in API level Build.VERSION_CODES.JELLY_BEAN_MR1 and above, if they are

      • defined as public
      • annotated with JavascriptInterface

sample.html

WebView addJavascriptInterface Example





Web To Android

MainActivity.kt

class MainActivity : AppCompatActivity()
{
    @SuppressLint( "SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //webview loads sample html
        webview.loadUrl("file:///android_asset/sample.html")
        //enables javascript in webview
        webview.settings.javaScriptEnabled = true
        //injecting java object
        webview.addJavascriptInterface(JavascriptInterface(),"javascript_object")
    }

    private inner class JavascriptInterface
    {
        @android.webkit.JavascriptInterface
        fun showToast(text: String?)
        {
            //toasting the text
            Toast.makeText(this@MainActivity,text,Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy()
    {
        //removes the java object from webview
        webview.removeJavascriptInterface("javascript_object")
        super.onDestroy()
    }
}


how above code works?

      • JavaScript enabled.
      • Inject java object into webpage using addJavascriptInterface() method. It needs
        1. Java class object: The java class object which inject into webview
        2. String name: The name used to access java methods from JavaScript
        3. It’s better to remove java object from webview after the use

WebView evaluateJavascript example in Android

evaluatejavascript android

Let’s call javascript from Java. In this example, we receive the text from edittext and send it to the local HTML page. Use loadUrl() for below 4.4 and evaluateJavascript() works with KitKat and above.

sample.html

Android Javascript Ex




WebView

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //loads sample html
        webview.loadUrl("file:///android_asset/sample.html")
        //enables javascript in webview
        webview.settings.javaScriptEnabled = true
    }

    fun sendMessage(view: View?)
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            //calls when version code greater than or equal to KITKAT
            webview.evaluateJavascript("show(\"" + edittext.getText() + "\")",null)
        }
        else
        {
            webview.loadUrl("javascript:show(\"" + edittext.getText() + "\")")
        }
    }
}


Android WebView Browser example – Progress bar included

Finally, we are here. Let’s create a webview app browser. This browser has

      • ProgressBar support
      • Google search and load URL support
      • Download file support
      • YouTube video support
      • Navigate history and custom home page
      • Share Support

open your Android Studio.

Step 1

Start a new Android Studio project.

Application Name: WebView Browser
Company Domain: androidride.example.com

Check Include Kotlin Support.


Step 2

Select form factors and minimum SDK

Select API 15: IceCreamSandwich and Click Next.


Step 3

Add Empty activity to Project.


Step 4

Add INTERNET and WRITE_EXTERNAL_STORAGE permission in AndroidManifest.xml

AndroidManifest.xml



    
    
    
        
            
                

                
            
        
    


      • android:windowSoftInputMode=”stateAlwaysHidden|adjustNothing” – it helps by without adjusting our bottom bar layout and disable the focus in EditText while startup.

Step 5

build.gradle
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.androidride.webviewbrowser_kotlin"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    }

Step 6

Colors.xml


    #707cff
    #3250cb
    #ffa7b7
    #e0e0e0
    #1d1d1d

Step 7

Styles.xml
    
    

 



Step 8

activity_main.xml


    

        
            

            

            


    

    

    

    

        

        

        

        

        

    




      • android:layout_weight attribute used to hold widgets.
      • android:inputType=”textNoSuggestions” disable spell check
      • android:background=”?android:selectableItemBackground” – makes transparent

I have used vector asset icons, you can also access them by right clicking on res->New->Vector Asset->Click on clip Art and select your icons, you can change color and size. Click OK and Next.


Step 9

custom_progress.xml



    
        
            
                
                
            
        
    

    
        
            
                
                
            
        
    


Step 10

This browser has a simple home page, for that, we have to add local HTML file in the assets folder.

demo.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Android webview local file ex - androidride</title>
<style type="text/css">
h1
{
border:2px solid #707cff;
padding:5px;
color:#707cff;
margin-top:120px;
text-align:center;
background-color:white;
}
body
{
background-color:#F2F2F2;
}
</style>
</head>
<body>
<h1>ANDROIDRIDE</h1>
</body>
</html>

Step 11

MainActivity.kt
package com.example.androidride.webviewbrowser_kotlin

import android.annotation.SuppressLint
import android.app.Activity
import android.app.DownloadManager
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.support.v7.app.AlertDialog
import android.view.KeyEvent
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import android.util.Patterns
import android.view.inputmethod.InputMethodManager
import android.webkit.*

class MainActivity : AppCompatActivity()
{
var share_url:String? = null

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

        //loads local demo html file
		webview.loadUrl("file:///android_asset/demo.html")
        //toolbar set as actionbar
        setSupportActionBar(toolbar)
        //javascript enabled
        webview.settings.javaScriptEnabled = true
		
		//downloadlistener enabled
       webview.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
            //checking Runtime permissions
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            {
                if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    //Do this, if permission granted
                    downloadDialog(url, userAgent, contentDisposition, mimetype)

                } else {

                    //Do this, if there is no permission
                    ActivityCompat.requestPermissions(
                        this,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        1
                    )

                }
            } else {
                //Code for devices below API 23 or Marshmallow
                downloadDialog(url, userAgent, contentDisposition, mimetype)

            }
        }    





        webview.webChromeClient = object : WebChromeClient()
        {
            override fun onProgressChanged(view: WebView?, newProgress: Int)
            {
                //it calls when progress changed
                progressbar.progress=newProgress
                super.onProgressChanged(view, newProgress)

            if(newProgress==100)
            {
                //if progress completes, progressbar gets hidden
                progressbar.visibility = View.GONE
            }

            }


            override fun onReceivedIcon(view: WebView?, icon: Bitmap?) {
                super.onReceivedIcon(view, icon)
                //favicon of webpage
                //toolbar_search_imageview_favicon.setImageBitmap(icon)
            }
        }

        webview.webViewClient = object: WebViewClient()
        {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?)
            {
                //it calls when webpage gets started and shows ProgressBar.
                progressbar.visibility = View.VISIBLE
				
				if("file:///android_asset/demo.html" != url)
				{
                    //if url is demo html url, then don't set to edittext
                edit_text.setText(url)
				}
				else
				{
                    //edittext cleared
				edit_text.text.clear()
				}

                super.onPageStarted(view, url, favicon)
            }

            override fun onPageFinished(view: WebView?, url: String?)
            {
                //if webpage gets finished
                share_url=url

                super.onPageFinished(view, url)
            }

        }

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean
    {
        //when back button taps
        if(keyCode == KeyEvent.KEYCODE_BACK && this.webview.canGoBack())
        {
            webview.goBack()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    fun goBack(view:View?)
    {
        //webview goes to previous page if there is one.
        if(webview.canGoBack())
            webview.goBack()
    }

    fun goForward(view: View?)
    {
        //webview goes to forward page if there is one.
        if(webview.canGoForward())
            webview.goForward()
    }

    fun goHome(view:View?)
    {
        webview.loadUrl("file:///android_asset/demo.html")
		}

    fun refresh(view: View?)
    {
        //it reload the current page
        webview.reload()
    }

    fun share(view: View?)
    {
        //Intent created
        val shareIntent = Intent()
        shareIntent.action=Intent.ACTION_SEND
        shareIntent.type="text/plain"
        //url of the sharing page
        shareIntent.putExtra(Intent.EXTRA_TEXT,share_url)
        shareIntent.putExtra(Intent.EXTRA_SUBJECT,"URL")

        startActivity(Intent.createChooser(shareIntent,"Share with your friends"))

    }

    fun go(view:View?)
    {
        //get text from edittext
     var text=edit_text.text.toString()
        searchOrLoad(text)
    }

    fun searchOrLoad(text:String)
    {
        //checks if it's a url or a string
        if(Patterns.WEB_URL.matcher(text.toLowerCase()).matches())
        {
            if (text.contains("http://") || text.contains("https://"))
            {
                webview.loadUrl(text)
            }
            else
            {
                webview.loadUrl("http://$text")
            }
        }
        else
        {
            //google search url
            webview.loadUrl("https://www.google.com/search?q=$text")
        }

        hideKeyboard()


        }

    private fun hideKeyboard()
    {
        //INPUTMETHODMANAGER service created.
        val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as  InputMethodManager
        //it hides softkeyboard
        inputMethodManager.hideSoftInputFromWindow(currentFocus.windowToken,InputMethodManager.SHOW_FORCED)
     }

    override fun onPause()
    {
        super.onPause()
        webview.onPause()
        webview.pauseTimers()
    }

    override fun onResume() {
        super.onResume()
        webview.onResume()
        webview.resumeTimers()
    }

fun downloadDialog(url:String,userAgent:String,contentDisposition:String,mimetype:String)
    {
        //getting file name from url
        val filename = URLUtil.guessFileName(url, contentDisposition, mimetype)
        //Alertdialog
        val builder = AlertDialog.Builder(this@MainActivity)
        //title for AlertDialog
        builder.setTitle("Download")
        //message of AlertDialog
        builder.setMessage("Do you want to save $filename")
        //if YES button clicks
        builder.setPositiveButton("Yes") { dialog, which ->
            //DownloadManager.Request created with url.
            val request = DownloadManager.Request(Uri.parse(url))
            //cookie
            val cookie = CookieManager.getInstance().getCookie(url)
            //Add cookie and User-Agent to request
            request.addRequestHeader("Cookie",cookie)
            request.addRequestHeader("User-Agent",userAgent)
            //file scanned by MediaScannar
            request.allowScanningByMediaScanner()
            //Download is visible and its progress, after completion too.
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            //DownloadManager created
            val downloadmanager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
            //Saving file in Download folder
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,filename)
            //download enqued
            downloadmanager.enqueue(request)
        }
        //If Cancel button clicks
        builder.setNegativeButton("Cancel")
        {dialog, which ->
            //cancel the dialog if Cancel clicks
            dialog.cancel()
        }

        val dialog:AlertDialog = builder.create()
        dialog.show()

    }

}

Hey… Thanks for scrolling. If you find anything useful in this post, please share it.

Conclusion

WebView has an important role in Android programming. With a few lines of code, beginners can also easily load web pages in their app. You have learned to download the file and run javascript using Android WebView. I am sure that these examples make you better dealing with WebView. This is a small guide about WebView. You can also find more information from below links.