Author

admin

Browsing

3 Flutter FlatButton Or Flutter Text Button Examples With Tutorial

flutter text button flatbutton
There are many widgets in Flutter to make a better user interface. In every UI, Buttons have their own important role.

From this post, you will start to learn about the Flutter button widgets. Such as FlatButton, RaisedButton, OutlineButton, and more.

So let’s start with Flutter FlatButton, and it is also called Flutter Text Button.

Flutter FlatButton

flutter flatbutton or flutter text button
flutter flatbutton or flutter text button

Text Button ??

Yes, Because by default, it’s just a black text or label without any

  • borders
  • elevation

You can use flatbutton in toolbars, dialogs, cards, and where ever enough space to add. Flatbutton also make the icon widget using FlatButton.icon().

FlatButton Simple Example

So let’s start programming and make a simple FlatButton like below.

flutter flatbutton example

 

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FlatButton(
        child: Text('FlatButton'),
        color: Colors.white,
        onPressed: () {
          print("FlatButton tapped");
        },
      ),
    );
  }
}

 

  • App gets started execution from main method. At last, build() method renders FlatButton with the help of MaterialApp.
  • If you do not use the MaterialApp in above code, it could result in No directionality widget found error.
  • I have used white color as FlatButton background using the color property. Otherwise, you could get a black screen with debug banner.
  • Already told you FlatButton text color is black by default

Check it out by removing color: Colors.white line from above code and reload.

FlatButton Properties

Let’s talk about the properties of FlatButton.

flatbutton onpressed example

1. VoidCallback onPressed: It gets called when FlatButton is tapped, You need to pass VoidCallback method, means no arguments and no return value.


For ex: void myFunction();

If you haven’t provided onPressed property or specified null value, then the button will look like in the first one from the above image.

If you have given a method name or anonymous function then the button will look like in the second one.

Okay. How to provide values to onPressed property.

  1. Using anonymous function

  2. 
    FlatButton(  
                onPressed: () {
               //implement your code.
    },
               .....
     ),
    
    
  3. Using function name

  4. void flatButtonTapped(){
      
    }
    
    FlatButton(onPressed: flatButtonTapped,
    
    )
    
    

    You don’t need to give parentheses ‘()’ here. Only the function name. Download all source code from the top link.

    2. VoidCallback onLongPress
    This property gets called when a long tap occurs. Just like onPressed property, pass an anonymous function or method name.

    
    FlatButton(onLongPress: (){},
    
    

    3. ValueChanged onHighlightChanged
    flatbutton highlight changed
    onHighlightChanged calls when you click down or up the button. When the button clicks down, it gives true value. false when button clicks up.

    
    FlatButton(
                child: Text('FlatButton'),
                onHighlightChanged: (value) {
                  print('onHighlightChanged value : $value');
                },
                onPressed: () {
                  //onpressed gets called when the button is tapped.
                },
              ),
    

    4. ButtonTextTheme textTheme

    It control the button’s text color based on the theme. There are 3 values

    1. ButtonTextTheme.Normal
    2. ButtonTextTheme.accent
    3. ButtonTextTheme.primary

    you can use like this

    
    textTheme: ButtonTextTheme.normal.
    
    

    It shows color based on your theme and swatch.

    5. Color textColor

    flatbutton textcolor example

    It determines button label’s or text color.

    
    FlatButton(
                onPressed: () {},
                child: Text("Login"),
                textColor: Colors.indigo,
              ),

    6. Color disabledTextColor

    flatbutton disabled text color example

    The color is used to display when the button is disabled. set null to onPressed.

    
    FlatButton(
                    child: Text('Flat Button - Default Disabled Text Color'),
                    onPressed: null,
                  ),
                  FlatButton(
                    child: Text('Flat Button - Custom Disabled Text Color'),
                    onPressed: null,
                    disabledTextColor: Colors.black54,
                  ),

    7. Color highlightColor

    Highlight property uses to highlight the button when it pressed. After the tap event, highlightColor spreads to fill the whole button and fade out.

    flatbutton high light color

    
    FlatButton(
              padding: EdgeInsets.all(80),
              highlightColor: Colors.redAccent,
              child: Text('FlatButton - highlight Color'),
               onPressed: () {
                //onpressed gets called when the button is tapped.
                print("FlatButton tapped");
              },
            ),
    

    8. Color splashColor

    When the button tapped, splashColor or tap event behaves as something falls into the liquid.

    splash color example

    
    FlatButton(
                       child: Text('Button'),
                       onPressed: (){},
                       splashColor: Colors.red,
            )
    

    9. Brightness colorBrightness

    flatbutton brightness example

    It’s used to increase the readability of text in Button. Use Brightness.light for light and Brightness.dark for dark background color.

    
    FlatButton(
                    child: Text('FlatButton - Brightness.light'),
                    colorBrightness: Brightness.light,
                    color: Colors.limeAccent,
                    onPressed: () {
                      //onpressed gets called when the button is tapped.
                      print("flat button tapped");
                    },
                  ),
                  FlatButton(
                    child: Text('FlatButton - Brightness.dark'),
                    colorBrightness: Brightness.dark,
                    color: Colors.deepPurple,
                    onPressed: () {
                      //onpressed gets called when the button is tapped.
                      print("flat button tapped");

    10. EdgeInsetsGeometry padding
    padding property helps us to specify the padding of FlatButton internal child. Here internal child is Text widget.

    
    FlatButton(
                    child: Text('FlatButton'),
                    onPressed: () {},
                    padding: EdgeInsets.all(50),
                    color: Color(0xFFFFD8C8),
                  ),
    • EdgeInsets.all() – Give enough padding to all sides of button’s text. Above code will apply 50 padding for all sides of the Text(Top, Bottom, Left and Right).

    • EdgeInsets.only() – It gives padding to the only specified side. You can specify one or more sides like below.

    flutter padding - EdgeInsets.only(top,left, right)

    
      FlatButton(
                    child: Text('FlatButton'),
                    onPressed: () {},
                    color: Color(0xFFFC6453),
                    padding: EdgeInsets.only(top: 10, left: 30, right: 20),
                  ),
    

    • EdgeInsets.symmetric() – You can provide values in horizontal and vertical directions.
    
      FlatButton(
                    child: Text('FlatButton'),
                    onPressed: () {},
                    color: Color(0xFF534858),
                    colorBrightness: Brightness.dark,
                    padding: EdgeInsets.symmetric(horizontal: 50),
                  ),
    
                  FlatButton(
                    child: Text('FlatButton'),
                    onPressed: () {},
                    color: Color(0xFF534858),
                    colorBrightness: Brightness.dark,
                    padding: EdgeInsets.symmetric(vertical: 50),
                  ),
                  Padding(
                    padding: EdgeInsets.all(10),
                  ),
                  FlatButton(
                    child: Text('FlatButton'),
                    onPressed: () {},
                    color: Color(0xFF534858),
                    colorBrightness: Brightness.dark,
                    padding: EdgeInsets.symmetric(horizontal: 50, vertical: 30),
                  ),
    
    

    11. ShapeBorder shape

    Shape property gives different options to make different shapes of flatbutton. Let’s make a rectangle FlatButton using shape property with the help of Border.all().

    flatbutton border all shape

    FlatButton(onPressed: (){}, child: Text('OK'),
              shape: Border.all(width: 2.0, color: Colors.pink),),
    
    
    • Border width is 2.0 and color is pink.

    StadiumBorder shape

    
     FlatButton(
                    onPressed: () {},
                    child: Text('StadiumBorder'),
                    shape: StadiumBorder(),
                    color: Colors.pink,
                    textColor: Colors.white,
                  ),
    

    CircleBorder

    FlatButton(
                    onPressed: () {},
                    child: Text('OK'),
                    shape: CircleBorder(),
                    color: Colors.pink,
                    textColor: Colors.white,)
    
    

    CircleBorder with Side

    
     FlatButton(
                    onPressed: () {},
                    child: Text('OK'),
                    shape: CircleBorder(
                      side: BorderSide(
                        color: Colors.pink,
                      ),
                    ),
                  )
    

    Rounded Rectangle Border

    FlatButton(
                    child: Text('Rounded Rectangle Border'),
                    onPressed: () {},
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(15)),
                    color: Colors.pink,
                    textColor: Colors.white,
                  )
    

    Beveled Rectangle Border

    FlatButton(
                    onPressed: () {},
                    child: Text('Beveled Rectangle Border'),
                    shape: BeveledRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                    color: Colors.pink,
                    textColor: Colors.white,
                  ),

    Outline Input Border

    FlatButton(
                    onPressed: () {},
                    child: Text('Outline Input Border'),
                    shape: OutlineInputBorder(),
                    color: Colors.pink,
                    textColor: Colors.white,
                  ),

    YOu can create underline using shape.

    Underline Input Border

    flatbutton underline input border

     FlatButton(
                    onPressed: () {},
                    child: Text('Underline Input Border'),
                    shape: UnderlineInputBorder(),
                    color: Colors.pink,
                    textColor: Colors.white,
                  ),

    FlatButton.Icon Example

    FlatButton.Icon Example
    Let’s create the Icon button using FlatButton.Icon

    
    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'FlatButton Icon Ex',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: Scaffold(
            appBar: AppBar(title: Text('FlatButton Icon Example'),
            centerTitle: true,),//it makes appbar title to center
            body: Center(
              child: FlatButton.icon(
                icon: Icon(Icons.add_alarm),//icon image
                label: Text('Add alarm'),//text to show in button
                textColor: Colors.white,//button text and icon color.
                color: Colors.green,//button background color
                onPressed: () {},
              ),
            ),
          ),
        );
      }
    }
    
    • Provided icon and label to FlatButton.icon()

    Flutter FlatButton onPressed Example – Counter Button


    flatbutton onpressed example
    In this example, you will learn how to change count using Flutter FlatButton. Final output will be like above image. Okay, Let’s start.

    
    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State {
      int counter = 0;
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('FlatButton onPressed Example'),
            ),
            body: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Center(
                  child: Text(
                    '$counter',
                    style: TextStyle(fontSize: 60.0),
                  ),
                ),
                SizedBox(
                  height: 20,
                ),
                FlatButton(
                  child: Text('CHANGE COUNT'),
                  onPressed: (){
                    setState(() {
                      counter = counter + 1;
                    });
                  },
               color: Colors.red,
                  textColor: Colors.white,
                ),
              ],
            ),
          ),
        );
      }
    }
    
    
    
    • Application starts execution from main() function.
    • The build() function builds user interface.
    • when we tap on the button, it increases counter variable by 1 and also calls setState().
    • The setState() function calls build() method again.

    Assume you liked this post, please share it with your family and friends.

7 Flutter Commands & Command Line Options You Must Know : Create New Project, Run & More Commands Using CLI

flutter create new project command line options cli create flutter app
In this post, you will learn about flutter terminal commands and command-line options. Using Flutter command-line interface (CLI), you can perform lots of operations in your project.

Before that make sure you have downloaded Flutter SDK and updated path variable if you are using Windows.

If you haven’t, you can use Flutter Android Studio post to do that.

You could run below commands in flutter console too.

flutter console terminal

This is Flutter console. You can find it in Flutter SDK.

Let’s start…

7. Flutter clean – Reduces Project Size by deleting build and .dart_tool directories.

When I created a simple flutter app, it’s size only below 200 kb but after a run in an emulator, Its size largely increases and takes more than 300 MB.

So if you have a low-configuration PC and you are learning flutter by making different apps. That might takes lots of memory in your device.

So just use below command in the root folder of the project.

flutter clean
flutter clean
flutter clean command
  • Using “flutter clean” command, you can reduce flutter project size. The command just deletes the build directory and some other files.

6.Flutter build – List Build Commands

For publishing your flutter app, you need to make binaries for Android and Ios. The build command by default makes a release flavor of the app.

flutter build

flutter build
  • It helps to list build formats of flutter
flutter build appbundle - build an appbundle
  • Recommended to build appbundle than apk.
flutter build apk 
  • It builds fat apk.
flutter build apk --split-per-abi 
  • Above command creates apks based on ABI.
flutter build ios 
  • Creates binaries for Ios.

5. Flutter channel – List Different Flutter Source Code Branches

Flutter channel means a git branch where we get Flutter source code. It could be used to change different branches such as master, dev, beta, and stable.

Just run “flutter channel” to find out.

flu
flutter channel
  • The channel with star symbol is you are currently using.
  • Here I am using stable channel and stable is recommended for product development.

Let’s change the channel…

flutter channel [channel_name] – this is syntax, let’s change stable to master.

flutter channel master
how to change flutter channel
change flutter channel to master
  • run “flutter upgrade” to ensure you are on the latest build.

4. Flutter run – Run Flutter Project

If you have created your flutter project, then you can run it on any devices or emulators using the run command. While using the run command, it must be called from the root directory of the project. you can use cd command for that purpose.

cd flutter_app
flutter run

    • If there are no emulators and devices connected, cmd will show “No supported devices connected”.
    • The app will get loaded and start running, If single device get connected,.
    • Multiple devices get connected, specify one device id with “flutter run -d” command
flutter run & fluttter run -d
flutter run & fluttter run -d
      • Just look at the above image, I just run “flutter run” and I got two devices, emulator and a physical device.
flutter run -d emulator-5554
    • Here I use emulator-5554 as device id.
  • If you want to run app on all devices, run “flutter run -d all” command.
  • By default, the debug version of the app will run on your device. It supports hot reload and fine for testing purposes.
  • There are other build flavors you can use like profile, flavor, and release.
  • the release version is for when you ready to publish it in play store or Appstore and it is not supported for emulators.
flutter run --release
  • If you use above command, you could see that the debug banner is gone.

3.flutter create – Create new flutter project Using Command Line

This command is used to create flutter projects, such as Flutter application, package, plugin, and module.

flutter create [output_directory_name or project_name]
  • Creates a Flutter app project
flutter create flutter_app
  • Creates a flutter app named “flutter_app”.
create flutter app flutter create new project command line
flutter create new project command line
  • After running above command, necessary files will be created on the specified name.
  • project name – It’s recommended to use lowercase with underscores.
  • If you run flutter create with existing flutter project name then the project will be recreated and if there are any files is missing, that too recreated again.
flutter creates project again
flutter recreates project
  • I have deleted main.dart file in the lib folder, now it recreated.

Let’s check how to create a package using flutter commands.

flutter create -t package flutter_package
  • Creates a package named flutter_package.
flutter create package
flutter create package
  • You can use -t or –template to specify the flutter project.

Let’s create a plugin project with flutter create command.

flutter create -t plugin flutter_plugin
  • It creates plugin project named flutter_plugin.
  • By default, swift is used as ios language, Kotlin for Android.

we can change that by using the below command.

flutter create -t plugin -i objc -a java my_flutter_plugin
  • Here -i means ios language – objc used, -a means android language.
  • You can remove -t plugin, if you are making Flutter application

Let’s create a project with our own package name and description, use below code

flutter create --org com.androidride --description "simple example" my_flutter_app
  • It creates a package name with “com.androidride”, you can view description in README.md

2.Flutter doctor – Diagnoses Flutter system environment.

This command diagnoses our system and tells us is everything fine or any issues need to treat just like a doctor.

If there are no issues, you are good to go. You don’t need to worry about all issues. For example, you are making a flutter app in VS Code, So you can avoid problems associated with Android Studio.

For example, Flutter plugin not installed in Android Studio like error.

flutter doctor

flutter doctor

  • Here I have one issue because I haven’t connected any devices.

Okay… Let’s know more details by running

flutter doctor -v

flutter doctor -v

  • Using the above image, we can understand that flutter doctor -v  gave more details about our Flutter development environment and tools.

1. flutter help

Just like the name it helps developers to find other commands and tells us how to use them just like a senior developer who is sitting nearby you. So I think, you don’t need to remember all commands I told above, Just remember this one.

flutter help
  • flutter -h and flutter –help give you the same results.
flutter help command
flutter help
flutter help -v
  • The above command gives a verbose output of flutter help.
flutter help [command]
  • Using the above syntax, we can check how other commands work.
flutter help create
  • Above command helps us to know more about create command.
flutter help create
flutter help create

Flutter Other Commands

Now I will show you some other commands with fewer details that helped me while I create flutter apps.

  • flutter doctor –android-licenses – It helps to accept all android licenses.
  • flutter logs – Shows logs generated by flutter apps in emulators and devices.
  • flutter analyze – It guides to make better code.
  • flutter config – Configures Flutter SDK and other settings.
  • flutter config –android-sdk “SDK_PATH”  – set Android SDK path.
  • flutter config –android-studio-dir “ANDROID_STUDIO_DIRECTORY_LOCATION” – sets Android Studio directory location
  • flutter upgrade – upgrade Flutter SDK to latest version
  • flutter downgrade – downgrade Flutter SDK to lower version
  • flutter pug get – pub is dart’s package manager, this command installs packages. The same function as packages get in Android Studio and Get packages in VS code.
  • flutter pub upgrade – upgrade packages to the latest version.
  • flutter emulators – shows available emulators.
  • flutter devices – shows connected emulators and devices
  • flutter screenshot – Takes screenshot from emulator or device
  • flutter screenshot -o C:\Users\Admin\Desktop\screenshot.png – Takes screenshot and stores in Desktop. (Windows users)

That’s all for now. Thank you. If you like this post, please share it with your friends and family.

How To Install Flutter In Android Studio In Windows : Flutter Android Studio Set Up Tutorial

how to install flutter in android studio in windows 10
Welcome to our first Flutter Android Studio tutorial.

Let’s start by talking about Flutter.

Google has introduced its software development kit Flutter in 2017. Using Flutter, you can develop applications for Android, ios, Mac, Windows, Linux, and More.

If you are making an app for Android and ios. You can consider using Flutter, which helps you to make both in one codebase.

So in this post, you will learn,

I am assuming that you have downloaded

and know, how to create an android project, emulator also.

How To Download Flutter SDK In Windows

how to install flutter in android studio in windows

download flutter sdk windows

  • While scrolling down, you will see a blue button with flutter latest SDK version in a zip file, just click on it.
  • Download begins…

Extract download flutter sdk windows

  • After the download, Extract the zip file

 

flutter sdk windows

  • Just cut and paste the extracted file in C drive, just like above. You can choose your suitable location except for Program Files in C drive.
  • Just click on the extracted directory.

flutter sdk

 

  • Click on flutter.

flutter console

  • This is Flutter software development kit. Here you can click on flutter console and check flutter commands.

flutter console terminal

  • This is flutter console window.
  • click on bin folder.

flutter bin directory

  • We need to update the PATH variable with “…/flutter/bin”, then only we can run flutter commands from any command prompt.
  • So copy the path with “flutter/bin” like shown above.

How To Update Path Variable With Flutter SDK Path In Windows

environment variable flutter setup

  • Search “env” on the search bar and click on “Edit environment variables for your account”.

update path variable with flutter

  • Click on the path field -> Edit -> New -> Paste it in the empty field. Just like above.
  • Click Ok.

create new path variable flutter

If the Path variable doesn’t exist, you need to create one. By clicking New->Providing values in each field (name and value) and click OK (just like shown above).

flutter doctor command check to install flutter plugin

  • Open the command prompt, and run the “flutter doctor” command.
  • If there is any problem you will see the red cross mark.
  • Here I got errors because flutter and dart plugin are unavailable, let’s clear it now.

How To Install Flutter Plugin In Android Studio

plugins android studio

  • Open Android Studio
  • If you don’t get a window like the above image.
    You may not close your last opened project. So just close your project, File -> Close Project.
  • Click on “Configure“.

plugins android studio 2

  • Next click on the “plugins” items from the drop-down menu.
  • flutter marketplace
  • Next, we have to find the flutter plugin from the marketplace. Make sure you are on the marketplace tab.
  • Then search “Flutter” in the search box and press Enter.
  • Click on the install button to install the flutter plugin.

flutter and dart plugin installation android studio

 

  • Dart plugin is also needed to make flutter applications. You don’t need to install separately. Just click on ‘Install‘ on the dialog box.
  • It will automatically download both.

restart android studio ide

  • Now click on the Restart IDE button to restart the Android Studio.

restart android studio ide dialog

  • In the next alert dialog box, “Restart Android Studio to activate changes in plugins?“. Click on Restart.

start a new flutter project in android studio

  • After the restart, now you can see “Start a new flutter project” item in the window.
  • That means you have successfully installed a flutter plugin in Android Studio.
  • But check again to confirm our system is ready to create flutter applicaions using flutter doctor command.

check flutter setup

  • Everything fine now.

How To Create Flutter Project In Android Studio

start a new flutter project in android studio

  • Click on “Start a new Flutter project”.

flutter project flutter application android studio

 

  • Select “Flutter Application” and click “Next”.

How To Change Flutter SDK Path In Android Studio

new flutter application android studio

 

  • I just let the project name as ‘flutter_app’. After that, one of the important step is to change the Flutter SDK path.
  • Click on Flutter SDK path (3 dot) button.

flutter sdk path set in android studio

  • Now you have to select the flutter SDK location, for me, it’s in C drive.  Expand drives by clicking on it.
  • After selecting flutter folder just click OK.

set flutter sdk path

  • Flutter SDK path is set now, then click Next.

change package name of flutter project

 

  • Change package name if you want.
  • I have changed to “com.androidride” , leave others, and click Finish.

How To Run Flutter Project In Android Studio

flutter run project android studio

 

  • After the build, the project will shown up just like above.
  • Like Android Project, Select your emulator and click on Run button.

run flutter app

  • The flutter application is ready now.

How To Open Existing Flutter Project In Android Studio

Method I – Drag And Drop Flutter Project To Android Studio

open existing flutter project in android studio

 

  • Before drag and drop your project, make sure you have installed the flutter plugin in Android Studio.

Method II – Using Open An Existing Android Studio Project

open existing flutter project in android studio

 

  • Click on “Open an Existing Android Studio project “.

open existing flutter app

  • Now you have to find the location of your flutter project. Here, my fluter project is located at desktop.
  • After selecting your project, just click OK.
  • The project is ready now.

I believe that this post will help you start your flutter journey. If you like this post, please share it with your family and friends. Thank you.

3 Android RecyclerView Load More On Scroll Examples

android recyclerview load more on scroll example

We are using lots of apps that load data while we scrolling. Facebook, Instagram, and more apps using this technique. This technique helps users to wait less time.

So if you are planning to make an app like that, using RecyclerView. Then this post is for you.

In this post, You will learn how to use Load More on Scroll or pagination or endless scrolling or infinite scroll or whatever you call, with RecyclerView.

Before that, I recommend reading our RecyclerView Tutorial Guide.

This post is not dealing with the pagination library.

How To Implement Pagination In Android RecyclerView

In this post, I am going to talk about two methods, that implement pagination in RecyclerView. But in both methods, we will use scroll Listener with RecyclerView to listen to scroll events. When RecyclerView scrolls, onScrolled() method gets called.

So first learn how to add OnScrollListener with Recyclerview.

How To Add OnScrollListener With RecyclerView


    //attaches scrollListener with RecyclerView
        recyclerview.addOnScrollListener(object : RecyclerView.OnScrollListener()
        {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int)
            {
                super.onScrolled(recyclerView, dx, dy)

              

            }
            })


Simple Android RecyclerView Load More On Scroll Example

Let’s make a linear list Using RecyclerView and add an endless scroll feature.

pagination in android recyclerview

After the implementation of scroll listener, we should do the following

  • we use findLastCompletelyVisibleItemPosition() to get the position of last visible item.
  • Use a variable which checks progressbar loading or not
  • If last item reached and progressbar not loading, loadmore() gets called. Using Handler, we add “load” in list.
  • When adapter checks list, ProgressBar gets added.
  • Next data chunks received, ProgressBar gets removed and data got added.
  • For showing different View types. here
    1. Data row
    2. ProgressBar

    Make use of getViewType() method in RecyclerView.Adapter.

MainActivity.kt

class MainActivity : AppCompatActivity()
{
    //handler instance
    var handler: Handler = Handler()
    //list for holding data
    lateinit var list : ArrayList

    lateinit var adapter : RecyclerViewAdapter
    //Variable for checking progressbar loading or not
    private var isLoading: Boolean = false
    lateinit var layoutManager : LinearLayoutManager



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

        layoutManager = LinearLayoutManager(this)
        //attaches LinearLayoutManager with RecyclerView
        recyclerview.layoutManager = layoutManager

        list = ArrayList()

        load()

        adapter = RecyclerViewAdapter(list)

        recyclerview.adapter = adapter

        addScrollerListener()

    }

    private fun addScrollerListener()
    {
        //attaches scrollListener with RecyclerView
        recyclerview.addOnScrollListener(object : RecyclerView.OnScrollListener()
        {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int)
            {
                super.onScrolled(recyclerView, dx, dy)

                if (!isLoading)
                {
                    //findLastCompletelyVisibleItemPostition() returns position of last fully visible view.
                    ////It checks, fully visible view is the last one.
                    if (layoutManager.findLastCompletelyVisibleItemPosition() == list.size - 1)
                    {

                        loadMore()
                        isLoading = true

                    }
                }

            }
            })
    }

    private fun loadMore()
    {
        //notify adapter using Handler.post() or RecyclerView.post()
        handler.post(Runnable
        {
            list.add("load")
            adapter.notifyItemInserted(list.size - 1)

        })

        handler.postDelayed(Runnable {

            //removes "load".
            list.removeAt(list.size - 1)
            var listSize = list.size

            adapter.notifyItemRemoved(listSize)
            //sets next limit
            var nextLimit = listSize + 10

            for(i in listSize until nextLimit)
            {
                list.add("Item No $i")
            }

            adapter.notifyDataSetChanged()
            isLoading = false

        },2500)
    }


    private fun load()
    {
        for(i in 0..9)
        {
            list.add("Item No: $i")
        }
    }

}

 

  • It's better to use Handler.post() or RecyclerView.post() while updating adapter when RecyclerView measures.
  • findLastCompletelyVisibleItemPosition() returns only completely visible Item's position, So make sure your last view is fully visible.
  • 2500 milliseconds - delay time

RecyclerViewAdapter.kt

package m.example.simplerecyclerviewloadmoreex_kotlin

import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.row.view.*

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import java.lang.IllegalArgumentException

class RecyclerViewAdapter(var list: ArrayList<String>) : RecyclerView.Adapter<RecyclerView.ViewHolder>()
{
    companion object
    {
        private const val VIEW_TYPE_DATA = 0;
        private const val VIEW_TYPE_PROGRESS = 1;
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewtype: Int): RecyclerView.ViewHolder
    {
        return when (viewtype)
        {
            VIEW_TYPE_DATA ->
            {//inflates row layout
                val view = LayoutInflater.from(parent.context).inflate(R.layout.row,parent,false)
                DataViewHolder(view)
            }

            VIEW_TYPE_PROGRESS ->
            {//inflates progressbar layout
                val view = LayoutInflater.from(parent.context).inflate(R.layout.progressbar,parent,false)
                ProgressViewHolder(view)
            }
            else -> throw IllegalArgumentException("Different View type")

        }
    }

    override fun getItemCount(): Int
    {
        return list.size
    }

    override fun getItemViewType(position: Int): Int
    {
        var viewtype = list.get(position)

        return when(viewtype)
        {//if data is load, returns PROGRESSBAR viewtype.
            "load"  -> VIEW_TYPE_PROGRESS
            else -> VIEW_TYPE_DATA
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, p1: Int)
    {

        if (holder is DataViewHolder)
        {
            holder.textview.text = list.get(p1)
        }
    }

    inner class DataViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
    {
        var textview = itemView.textview

        init {
            itemView.setOnClickListener {
                Toast.makeText(itemView.context,list.get(adapterPosition),Toast.LENGTH_LONG).show()
            }
        }
    }

    inner class ProgressViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

}

 

  • getItemViewType(int position) method returns VIEW_TYPE_PROGRESS, if data is "load". Otherwise, it returns VIEW_TYPE_DATA.
  • Based on ViewType, In onCreateViewHolder layout will get inflated.

Grid RecyclerView Pagination Example - Different Approach

Now we will make a Grid RecyclerView with pagination. Sometimes we need to load data before the last item loads.

grid android recyclerview infinite scroll example pagination

For that purpose, you can make use of this approach.

Okay, what we do in this approach.

we define 3 variables, visibleThreshold, lastVisibleItem, and totalItemCount.

  • visibleThreshold : limit of items that user want to see before loading next items
  • lastVisibleItem : just like name, last visible item position in adapter
  • totalItemCount : No.of items in adapter

after the scroll listener setup,

  • When onScrolled() gets called, just checks totalItemCount <= lastVisibleItem + visibleThreshold with isLoading : variable for storing progressbar state.
  • if both are true, next chunks of data get loaded
class MainActivity : AppCompatActivity()
{
    lateinit var list : ArrayList
    lateinit var adapter : RecyclerViewAdapter
    private var isLoading: Boolean = false
    lateinit var gridlayoutManager : GridLayoutManager


    private var visibleThreshold = 5
    private var lastVisibleItem = 0
    private var totalItemCount = 0

    //handler instance
    private var handler: Handler = Handler()

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

        //no of columns or span in the grid.
        var columns = 2

        gridlayoutManager = GridLayoutManager(this, columns)
        recyclerview.layoutManager = gridlayoutManager

        load()

        adapter = RecyclerViewAdapter(list)

        recyclerview.adapter = adapter

        addScrollerListener()

        gridlayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup()
        {
            //Each item occupies 1 span by default.
            override fun getSpanSize(p0: Int): Int
            {
                return when (adapter.getItemViewType(p0))
                {
                    //returns total no of spans, to occupy full sapce for progressbar
                    RecyclerViewAdapter.VIEW_TYPE_PROGRESS -> gridlayoutManager.spanCount
                    RecyclerViewAdapter.VIEW_TYPE_DATA -> 1
                    else -> -1
                }
            }
        }
    }

      private  fun addScrollerListener()
        {
            recyclerview.addOnScrollListener(object : RecyclerView.OnScrollListener()
            {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int)
                {
                    super.onScrolled(recyclerView, dx, dy)

                    //total no. of items
                    totalItemCount = gridlayoutManager.itemCount
                    //last visible item position
                    lastVisibleItem = gridlayoutManager.findLastCompletelyVisibleItemPosition()

                    if(!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold))
                    {
                        loadMore()
                        isLoading = true
                    }
                }
            })
        }



    private fun loadMore()
    {
        handler.post(Runnable
        {
            //adds load item in list
            list.add("load")
            adapter.notifyItemInserted(list.size - 1)

        })

        recyclerview.postDelayed(Runnable {

            //removes load item in list.
            list.removeAt(list.size - 1)
            var listSize = list.size

            adapter.notifyItemRemoved(listSize)
            //next limit
            var nextLimit = listSize + 10

            for(i in listSize until nextLimit)
            {
                list.add("Item No $i")
            }

            adapter.notifyDataSetChanged()
            isLoading = false

        },7000)

    }

    private fun load()
    {
        list = ArrayList()

        for(i in 0..9)
        {
            list.add("Item $i")
        }
    }

}

  • Make ProgressBar width to maximum using setSpanSizeLookup() method

 

RecyclerViewAdapter.kt

 

class RecyclerViewAdapter(var list: ArrayList<String>) : RecyclerView.Adapter<RecyclerView.ViewHolder>()
{
    companion object
    {
        const val VIEW_TYPE_DATA = 0;
        const val VIEW_TYPE_PROGRESS = 1;
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewtype: Int): RecyclerView.ViewHolder
    {
        return when (viewtype)
        {
            VIEW_TYPE_DATA ->
            {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.row,parent,false)
                DataViewHolder(view)
            }

            VIEW_TYPE_PROGRESS ->
            {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.progressbar,parent,false)
                ProgressViewHolder(view)
            }
            else -> throw IllegalArgumentException("Different View type")

        }
    }

    override fun getItemCount(): Int
    {
        return list.size
    }

    override fun getItemViewType(position: Int): Int
    {
        var viewtype = list.get(position)
        return when(viewtype)
        {
            "load"  -> VIEW_TYPE_PROGRESS
            else -> VIEW_TYPE_DATA
        }
    }

    override fun onBindViewHolder(p0: RecyclerView.ViewHolder, p1: Int)
    {

        if (p0 is DataViewHolder)
        {
            p0.textview.text = list.get(p1)
        }
    }

    inner class DataViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
    {
        var textview = itemView.textview

        init {
            itemView.setOnClickListener {
                Toast.makeText(itemView.context,list.get(adapterPosition),Toast.LENGTH_LONG).show()
            }
        }
    }

    inner class ProgressViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
    
}

Retrofit Android RecyclerView Infinite Scroll Example

In this example, we will load data from the internet using Retrofit2. You can download PHP(data.php) code from the Source Code link shown at the top.

I am using Android Studio 3.5.


Let's create a project.

In choosing your project window, click on "Empty Activity" and click Next.

Name: RetrofitRecyclerViewLoadMoreEx

Package name: androidride.com

Select language Kotlin

I am going to use AndroidX library, so make sure you tick on the androidx.* artifacts.
That's your choice, but I recommend to use this one.

Click "Finish".


add below dependencies

implementation 'com.squareup.retrofit2:retrofit:2.0.2'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'

implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
  • Gson converter : It helps to serialize and deserialize JSON data.

build.gradle(Module:App)

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

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

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'


    implementation 'com.squareup.retrofit2:retrofit:2.0.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.0.2'

    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'

}

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">Retrofit RecyclerView LoadMore Ex - Kotlin</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>

 

  • Don't forget to add INTERNET permission in AndroidManifest.xml like below

AndroidManifest.xml

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

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

    <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"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

Data.kt

package com.androidride.retrofitrecyclerviewloadmoreex

data class Data(var category: String)
{
    var title: String? = null
    var subtitle: String? = null

    init {
        this.category = category
    }
}

DataApi.kt

package com.androidride.retrofitrecyclerviewloadmoreex

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query

interface DataApi
{
@GET("data.php")
fun getData(@Query("index") index : Int): Call<List<Data>>
}
  • In Retrofit2, endpoints defined in Interface with special annotations.
  • This endpoint returns List.

MainActivity.kt

package com.androidride.retrofitrecyclerviewloadmoreex

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit


class MainActivity : AppCompatActivity()
{
    lateinit var list: ArrayList
    lateinit var adapter: RecyclerViewAdapter

    var notLoading = true
    lateinit var layoutManager: LinearLayoutManager
    lateinit var api: DataApi
    lateinit var retrofit: Retrofit


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


        list = ArrayList()
        adapter = RecyclerViewAdapter(list)
        recyclerview.setHasFixedSize(true)

        layoutManager = LinearLayoutManager(this)
        recyclerview.layoutManager = layoutManager
        recyclerview.adapter = adapter

        retrofit = RetrofitInstance.getRetrofitInstance()
        api = retrofit.create(DataApi::class.java)

        load(0)

        addscrolllistener()
    }

    private fun addscrolllistener()
    {
        recyclerview.addOnScrollListener(object : RecyclerView.OnScrollListener()
        {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int)
            {
                if(notLoading &&  layoutManager.findLastCompletelyVisibleItemPosition() == list.size -1 )
                {
                    list.add(Data("progress"))
                    adapter.notifyItemInserted(list.size - 1)
                    notLoading = false

                    val call: Call<List> = api.getData(list.size - 1)

                    call.enqueue( object :  Callback<List>
                    {
                        override fun onResponse(call: Call<List>?, response: Response<List>?)
                        {
                        list.removeAt(list.size - 1)
                        adapter.notifyItemRemoved(list.size)

                                if(response!!.body().isNotEmpty())
                                {
                                    list.addAll(response.body())
                                    adapter.notifyDataSetChanged()
                                    notLoading = true
                                }
                                else
                                {
                                    Toast.makeText(applicationContext,"End of data reached", Toast.LENGTH_LONG).show()
                                }

                        }

                        override fun onFailure(call: Call<List>?, t: Throwable?) {
                            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                        }
                    })
                }
            }
        })
    }

    private fun load(i: Int)
    {
        val call: Call<List> = api.getData(0)

        call.enqueue(object : Callback<List>
        {
            override fun onResponse(call: Call<List>?, response: Response<List>?)
            {
                if(response!!.isSuccessful)
                {
                    list.addAll(response!!.body())
                    adapter.notifyDataSetChanged()
                }

            }

            override fun onFailure(call: Call<List>?, t: Throwable?)
            {

            }
        })

    }
}


RetrofitInstance.kt

package com.androidride.retrofitrecyclerviewloadmoreex

import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class RetrofitInstance
{
    companion object
    {
        fun getRetrofitInstance(): Retrofit
        {
            val retrofit = Retrofit.Builder().baseUrl("https://www.androidride.com/").addConverterFactory(
                GsonConverterFactory.create()).build()

            return retrofit

        }
    }
}

  • For performing network requests, we need to create Retrofit Instance using Retrofit.Builder() using Base Url

RecyclerViewAdapter.kt

package com.androidride.retrofitrecyclerviewloadmoreex;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class RecyclerViewAdapter extends RecyclerView.Adapter
{

    public static final int TYPE_DATA = 0;
    public static final int TYPE_PROGRESS = 1;

    ArrayList list;

        public RecyclerViewAdapter(Context context,ArrayList list)
        {
            this.list = list;
        }


    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
    {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());

            if(viewType == TYPE_DATA)
            {
                return new DataHolder(inflater.inflate(R.layout.row,parent,false));
            }
            else
            {
                return new ProgressHolder(inflater.inflate(R.layout.progressbar,parent,false));
            }

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position)
    {
            if(holder instanceof  DataHolder)
            {
                ((DataHolder) holder).textTitle.setText(list.get(position).title);
                ((DataHolder) holder).textSubtitle.setText(list.get(position).subtitle);
            }
    }

    @Override
    public int getItemCount()
    {
        return list ==  null ? 0 : list.size() ;
    }

    @Override
    public int getItemViewType(int position)
    {
        if(list.get(position).category.equals("data"))
        {
            return TYPE_DATA;
        }
        else
         {
            return TYPE_PROGRESS;
         }
    }

    class DataHolder extends RecyclerView.ViewHolder
    {
        TextView textTitle,textSubtitle;

        public DataHolder(@NonNull final View itemView)
        {
            super(itemView);

            textTitle =(TextView)itemView.findViewById(R.id.title);
            textSubtitle = (TextView)itemView.findViewById(R.id.subtitle);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view)
                {
                    Toast.makeText(itemView.getContext(),"Clicked Item: "+list.get(getAdapterPosition()).subtitle,Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    class ProgressHolder extends RecyclerView.ViewHolder
    {
        public ProgressHolder(@NonNull View itemView)
        {
            super(itemView);
        }
    }
}


retrofit android recyclerview pagination example

Thanks for scrolling. If you have liked this post, please share it with your friends and family.

3 Reasons To Buy Head First Android Development – 2nd Edition

head first android development download

Do you want to learn, how to develop Android apps?

There’s only one way – write a lot of code! : Head First Android Development.

So in this post, I am talking about Head First Android Development – 2nd Edition, One of my favorite Android programming books. Actually the 3 reasons why I think it’s better to buy and also something you want to consider before buying.

So let’s start… and find out the reasons…

Check out other’s reviews, ratings and price by clicking below “View on Amazon” link.

    • It’s the Second Edition

By referring Second Edition you can understand that there is a successful First edition. After the victorious initial release in 2015, it got positive reviews all over the world. Experienced programmers and writers Dawn Griffiths and David Griffiths made the second part as well as the first version.

They included lots of basics stuff again. Such as Constraint layout, Support library, and RecyclerView – the book becomes a larger one and it pays off.

  • It’s From Head First – This Is Enough

Head First – For me, This one reason is enough to buy this book. Not only this book fan, but I am also a Head First fan too.

One minute if you don’t know about the Head First, it’s just a book series published by Oreilly. Head First released lots of books on topics like programming, Science and Mathematics.

Okay… But what makes Head First different from others?.

Because of their teaching style.

They prefer visual learning, The brain processes visual information 60,000 times faster than text and that helps you to grasp information easily.

Visual information holds in your memory better than large chunks of text.

Saying things repetitively in different ways that also attach the information in your head.

The next one I think is conversational style – they present information just like in a conversation. Because we pay more attention to the conversation than a lecture.

Head First books are not for read-only. You have to think, write and do challenges such as puzzles, quizzes and more.

However, in their way, they tried their maximum to tune our brain with humor and excitement with knowledge in each book I have read.

  • Step By Step App Making Process Makes You More Confident

Confidence – that’s my third reason why I recommend it. When you complete Head First Android Development, you will have the confidence to make your own apps. That’s how I did feel after finished.

The chapters in the book deal with creating a new app with a new concept or updating the existing one. Whatever you do, you will write a lot of code throughout the book. Remember the beginning?

Step by step you will learn to make more apps and more about Android.

In each chapter, difficulty level increases. But you won’t feel it as much as other books when compared to this one.

Okay. Let’s talk about the chapters, how it works for you?

The book starts with creating a basic Helloworld app, in that chapter you will learn how to set up Android Development Environment and a little about other basic building blocks of Android.

After that, you start to make an interactive app built by mainly Spinner and Button in the second chapter.

In the third chapter, you will learn how to use intents with activities inside your app and other apps.

After that, chapter 4, you will learn about how activities work? What happens or which method gets called in its lifecycle with the help of a stopwatch app.

Thenceforth in Views and ViewGroups chapter, you will get to know how to use GUI components and show you how LinearLayout and FrameLayout works.

How to make complex layouts using Constraint layout that will be learned in chapter 6 by making the “My Constraint Layout” app.

If you are a beginner and have a great idea for an app, the next chapter will help you to organize your ideas and make an awesome app. For example, you will make a starbuzz app from scratch.

Following this, you will understand the importance of the Android Support library, also learn how to make shortcuts in the app bar.

Android apps are running on different devices. What you do if you want your app to look different depending on the phone or tablet? There are 3 main chapters for dealing with that question with Fragments.

You will create a workout app that’s enough to deal with fragment lifecycle methods. The next chapter will help you to implement material design in-app with the help of Android Design Support Library.

You will see how to use tabs, toolbar, floating action buttons and snack bars.

In the 13th chapter, you will learn about an advanced type of list: RecyclerView. CardView also get introduced. You will build an app with these too.

The next chapter will show you how to show different sections of our app using navigation drawer.

The next 3 chapters will clear almost all your doubts about the SQLite database in Android. Only through making apps.

after that, you will get introduced to Services, which helps us to work in the background. such as downloading files.

oh, this is enough, I have almost summarized it. But the books contain a lot more than that.

  • Before Buying Head First Android Development – Second Edition

This book is enough for a beginner, but there is something you must consider while buying this one.

      1. You should know Java programming language
      2. This is not a reference book and it takes time to complete. Just reading isn’t the way to use this book.
      3. Second edition released in 2017, so Book uses Android Studio 2.3. So it little bit outdated now.
      4. It just introduces below topics, not a detailed tutorial
        • WebView – Don’t worry, our webview guide is here
        • Content Provider
        • Loaders
        • Broadcast Receivers
        • Testing like topics.

For Indian users, All Indian Reprints of O’Reilly are printed in Greyscale (B/W)

Conclusion

There are lots of books you can find about Android Programming. For me, Head First Android Programming – Second Edition will stay in front of them. When I started learning Android app development, I always roam around online tutorials and gets nowhere. But after reading Head First, It’s changed. It gives me enough information and confidence to make my own apps. Although it’s late to review this book, but still people searching about this book, talking about this. That’s why I reviewed it now. But for beginners, It’s still worth reading. If Head First releases the 3rd edition, I would definitely read it.

4 Ideas To Create Horizontal RecyclerView With Example

horizontal recyclerview android example
Do you want to make Horizontal RecyclerView?

Before jumping into tutorial, I would recommend reading RecyclerView In Android : The Ultimate Guide.

In this post, I will teach you how to make Horizontal RecyclerView In Android with 4 ideas. In the end, we will create a Horizontal RecyclerView project too.

Okay… Let’s start.

RecyclerView uses LayoutManager class to arrange its items, so below we are going to use the LayoutManager class to make it work.

1. Horizontal RecyclerView Using LinearLayoutManager

This is the first and most commonly used option to make Horizontal RecyclerView. LinearLayoutManager provides a constructor that we can change the orientation of RecyclerView.

LinearLayoutManager(Context context, int orientation, boolean reverseLayout)

val layoutManager = LinearLayoutManager(this@MainActivity,LinearLayoutManager.HORIZONTAL,false)
recyclerview.layoutManager = layoutManager

  • Here, we use “this” because RecyclerView uses in MainActivity. If you are using RecyclerView in fragment, you can use getActivity()
  • false : Do not reverse the layout.

2.Horizontal RecyclerView Using app:LayoutManager attribute





  • app:layoutManager=”androidx.recyclerview.widget.LinearLayoutManager”: sets LayoutManger for RecyclerView.
  • android:orientation=”horizontal” : Render RecyclerView in Horizontal.
  • For support library users, Use this app:layoutManager=”android.support.v7.widget.LinearLayoutManager”.

3. Horizontal RecyclerView Using GridLayoutManager

In this part, we use GridLayoutManager for creating horizontal RecyclerView. Use the below one.

GridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout)

spanCount: Number of rows or columns based on orientation.

  val gridLayoutManager = GridLayoutManager(this@MainActivity,1,GridLayoutManager.HORIZONTAL,false)
        recyclerview.layoutManager = gridLayoutManager


You can use XML way, just like below:

    app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
    android:orientation="horizontal"
    app:spanCount="1"

  • For support library users, app:layoutManager=”android.support.v7.widget.GridLayoutManager”

4. Horizontal Recyclerview Using StaggeredGridLayoutManager

In this section we can use StaggeredGridLayoutManager constructor, shown below:

StaggeredGridLayoutManager(int spanCount, int orientation)

 val staggeredGridLayoutManager = StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.HORIZONTAL)
        recyclerview.layoutManager = staggeredGridLayoutManager


In XML way

app:layoutManager="androidx.recyclerview.widget.StaggeredGridLayoutManager"
android:orientation="horizontal"
app:spanCount="1"

  • For support library users, Use app:layoutManager=”android.support.v7.widget.StaggeredGridLayoutManager”/li>

.

Horizontal RecyclerView In Android – Main Example

Let’s create a horizontal RecyclerView…

Just like below

Horizontal RecyclerView Android Example

Open Android Studio and start a new Android Studio project.

Application name : Horizontal RecyclerView Android Example.

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

If you are using the latest Android Studio versions, there will be a CheckBox with the text “Use androidx.* artifacts”. Make sure that’s checked, which creates our project with androidx library.
Click Finish.

build.gradle


apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

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

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'


}

colors.xml



    #008577
    #00574B
    #D81B60


strings.xml


    Horizontal RecyclerView Android Example

styles.xml



    
    

 


activity_main.xml



        

        

        


MainActivity.kt

class MainActivity : AppCompatActivity()
{
    val dataList = ArrayList()

    lateinit var adapter : RecyclerViewAdapter

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

        setupdata()

        adapter = RecyclerViewAdapter(dataList)


        //Using LinearLayoutManager

        val layoutManager = LinearLayoutManager(this@MainActivity,LinearLayoutManager.HORIZONTAL,false)
        recyclerview.layoutManager = layoutManager



        /*Horizontal RecyclerView using GridLayoutManager

        val gridLayoutManager = GridLayoutManager(this@MainActivity,1,GridLayoutManager.HORIZONTAL,false)
        recyclerview.layoutManager = gridLayoutManager

        */


        /*
            Horizontal RecyclerView using StaggeredGridLayoutManager

        val staggeredGridLayoutManager = StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.HORIZONTAL)
        recyclerview.layoutManager = staggeredGridLayoutManager

         */

        recyclerview.adapter = adapter
    }


    private fun setupdata()
    {
        dataList.add("ONE")
        dataList.add("TWO")
        dataList.add("THREE")
        dataList.add("FOUR")
        dataList.add("FIVE")
        dataList.add("SIX")
        dataList.add("SEVEN")
        dataList.add("EIGHT")
        dataList.add("NINE")
        dataList.add("TEN")
    }
}


item.xml






RecyclerViewAdapter.kt

class RecyclerViewAdapter(val dataList: ArrayList):RecyclerView.Adapter()
{

        inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
        {
            val textview = itemView.textview
        }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder
    {
            val inflater = LayoutInflater.from(parent.context)
            val view = inflater.inflate(R.layout.item,parent,false)

            return ViewHolder(view)
    }

    override fun getItemCount(): Int
    {
        return dataList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int)
    {
        holder.textview.text = dataList.get(position)
    }
}


Let’s run it and please share it with your friends, family, and co-workers.

RecyclerView With CheckBox In Android Example: 2 Examples And Tutorial About RecyclerView Adapter, Difference Between ListView & RecyclerView, and OnClickListener Will Help You To Know RecyclerView Better.

Android Recyclerview Simple Tutorial

RecyclerView??? Is that a View? What does it do?

How to use this one?

are these thoughts running through your head? then Go on.
Or
you know something about RecyclerView then Refresh your knowledge by reading this post.

In this article, you will learn about RecyclerView, RecyclerView Adapter, and a simple example that helps you to create your one.
At last, I will teach you how to use Checkbox with RecyclerView. Yes, you can scroll fearlessly without thinking about losing the selected states in CheckBox.

So fasten your seatbelts, let’s take-off now.

What Is RecyclerView In Android?

From the name, we can understand that it’s an Android View. Actually, It is a ViewGroup with scroll ability which works based on adapter principles.

In simple words, It helps us to show a large no. of data collections just like ListView and GridView.

If RecyclerView wants to show large no.of items, it does not create the same amount of views. It just creates the viewholders which hold the inflated view needed to fill the screen and some more.

After that when the user scrolls, it makes use of cached views. Yes, It recycles views, again and again, that’s why it got the name “RecyclerView”.

As a successor, It is far away from ancestors(ListView, GridView) by performances and abilities. By more features, it becomes a little bit complex too.

Let’s look up the history, ListView has been part of Android since 1.0, but each os releases, new features got added. Not in the case of ListView.

ListView simply defeated by developer’s needs such as different types of layouts and animation support. That’s where RecyclerView was born.

Finally in 2014 Android Lolipop introduced RecyclerView as a standalone support library.

After the arrival of the AndroidX library (after API level 28.0.0), RecyclerView changed its package name android.support.v7.widget.RecyclerView to androidx.recyclerview.widget.RecyclerView.

If you are using Android Studio, just add it to gradle and use.

8 Differences Between ListView And RecyclerView In Android

differences between listview and recyclerview in android

1. ViewHolder pattern
ViewHolder pattern is a strategy used to store view references in memory.

It reduces the number of calls to complicated and tedious findViewById(), which makes scrolling smooth.
,
In the case of ListView, it was optional, you can build your favorite list without any use of ViewHolder.

But when it comes to RecyclerView side, google developers make it as default for RecyclerView.

2. Re-Using views
Both ListView and RecyclerView support Reusing views. On the ListView side, it gives the option to reuse.

It’s the developer, who needs to take the action.

@Override
    public View getView(int position, View convertView, ViewGroup parent) 
{
     if(convertView == null)
     {
      //inflate your layout
     }
     //reuse convertView

}

Using the above example code, we can check the convertView is null or not. If it is null, that means there is no recycled view. Then we can inflate the layout.

If it is not null, means that not the first time, so we can use convertView and avoid layout inflation.

3. Layout Types

With ListView, you can easily make a list with simple and less code.

Code is a bit complex with RecyclerView, but it provides more options: horizontal, vertical list, grid, and staggered grid

You can also create your custom layout manager using RecyclerView.LayoutManager.

4.Animation Support

In the animation section, RecyclerView is far ahead from ListView. It’s not easy for beginners to make animations in ListView.

But RecyclerView shows Fade in, Fade out, translate and crossfade animations when you add, delete, move and update an item in RecyclerView.

This is default in RecyclerView because it internally uses the DefaultItemAnimator class. That’s why they gave that name.

If you don’t like these animations and want to make your animations make use of RecyclerView.ItemAnimator class.

5. Divider

ListView has divider by default.

The android:divider and android:dividerHeight attributes or setDivider(),setDividerHeight() helps you to make custom divider in ListView.

But RecyclerView doesn’t give these options.

But you can use the DividerItemDecoration class to make a simple divider or Make use of RecyclerView.OnItemDecoration class to decorate the view.

6. Click Events

One of the main disadvantages we face with RecyclerView is that it lacks OnItemClickListener. Because it’s not a subclass of AdapterView like ListView.

It provides RecyclerView.OnItemTouchListener to capture click events. It gives more control to the developer.

You can also use OnClickListener with views on the item.

7.Notify Methods
When notifying adapter, while data change occurs we can call notifyDatasetChanged() with ListView.

But ListView doesn’t know what had happened? It can be the addition, deletion or change of items in the dataset but don’t know what was happened.

For RecyclerView there are lots of notify* methods to inform, including notifyDatasetChanged().

Using the appropriate notify* method can invoke better animation in RecyclerView.

8. Header and Footer
It is easy to add Header and Footer in ListView using addHeaderView() and addFooterView().

But RecyclerView doesn’t have these methods instead it supports different types of view.

Finally, RecyclerView supports Nested Scrolling.

I think that’s enough for the comparison. So use them based on your needs. If you are a beginner in Android App Development, Learn ListView first then go with RecyclerView.

How To Use RecyclerView In Android?

RecyclerView is one of the most valuable widgets in Android development. Out of the box, RecyclerView is lazy. Because it has given responsibilities to different classes.

So before Using RecyclerView, you should know about these classes.

1)RecyclerView.Adapter

This is the most important class in RecyclerView. Same as other AdapterView, It connects the View(RecyclerView) and data.

RecyclerView has no default adapters, So you need to create a custom class by extending Recyclerview.Adapter.

It is responsible for

  • Creating ViewHolders
  • Binds data to ViewHolders.
  • Informs Recyclerview about dataset changes.

Most of the important methods in this class are:
i)OnCreateViewHolder() : This method is called when RecyclerView needed to create a viewholder.
ii)OnBindViewHolder(): Calls whenever needed to bind data with view in viewholder.
iii)getItemCount() : Used to return total number of items in the dataset (ArrayList, array etc).
iv)getItemViewType(): it returns the viewtype based on the position.

2) RecyclerView.LayoutManager

As the name says, it helps RecyclerView to manage layout by positioning each item.

Unlike ListView, RecyclerView shows child items in Horizontal, Vertical list, grid, and staggered grid because of LayoutManager.

Scrolling responsibility is also own by LayoutManager. When you scroll up in RecyclerView, LayoutManager moves your items up.
staggeredgridlayoutmanager gridlayoutmanager
It provides different classes for arranging items:

i)LinearLayoutManager: Creates vertical and horizontal lists.
ii)GridLayoutManager: Creates grid layouts.
iii)StaggeredGridLayoutManager: Creates StaggeredGrid layouts.
iv)WearableLinearLayoutManager: This class is for wearable devices.

3) RecyclerView.ItemDecoration

The name implies, it decorates RecyclerView’s item or view. It provides not only a divider, Using this abstract class you can draw four sides of the item. When using the divider as a view in XML, it decreases performance. That’s where the importance of this class comes through.

Version 25.1.0 Support library introduces the DividerItemDecoration class, to make a simple divider. Use addItemDecoration() method to add with RecyclerView. This class supports both horizontal and vertical orientations, so you can use it with any of your lists without any worries.

4) RecyclerView.ItemAnimator

Google developers gave more importance to animations in RecyclerView, So RecyclerView provides RecyclerView.ItemAnimator class for handling animations.

You can make custom animations using this class.

Just I said in ListView vs RecyclerView comparison, RecyclerView animates items when item adds, delete or any other move event happens because it internally uses DefaultItemAnimator.

But you can not see these animations when RecyclerView loading for the first time.

5) RecyclerView.ViewHolder
Android RecyclerView ViewHolder
You can consider ViewHolder as something which holds View.

Unlike ListView, we need to make custom ViewHolder class by extending RecyclerView.ViewHolder class.

In this subclass, we must store the item view’s references. This ViewHolder class contains additional information like its position in the layout.

Simple RecyclerView Example With CardView In Android Studio – OnClickListener Included


In this example, I will explain how to create RecyclerView in Android Studio in 10 simple steps with a detailed explanation. The final output will look like below.

Simple RecyclerView With  CardView Example In Android Studio
I assume that you have created a Project in Android Studio, then add these

STEP 1 – Add Dependencies In build.gradle

RecyclerView and CardView are support libraries, so you must add dependencies in your build.gradle file, If your app needs to support above API 28.0.0, you must use AndroidX libraries. otherwise, you can continue with the support library.

 
/* androidx library*/

    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'

/*
support library
 
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
*/

STEP 2 – Import RecyclerView In Android Studio

Just like ListView, just add it to your layout. here activity_main.xml





This code creates a RecyclerView widget with id “recyclerview”.

  • android:scrollbars=”vertical” – It creates vertical scrollbar to the RecyclerView. Otherwise user never get to know how long the RecyclerView is.
  • Use android.support.v7.widget.RecyclerView as root widget if you are using the support library, attributes are same as above.

STEP 3 – Create Row Layout For RecyclerView

In this step, we will create a layout and RecyclerView will show it as child items. Right-click on the layout folder in res directory. New->Layout Resource File-> put file name as row_layout.xml and put below code.


    



  • This code creates TextView inside CardView. You can use app: namespace to specify support library attributes.
  • if you are using support library, Use android.support.v7.widget.CardView.

STEP 4 – Create An Array And Pass It To RecyclerView Adapter

RecyclerView adapter needs data and layout. So here, we will create an array of months and pass it to the adapter class, which you are going to make in the next step.

class MainActivity : AppCompatActivity()
{

    var months_array = arrayOf("JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER")

    lateinit var adapter :RecyclerViewAdapter

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

        adapter = RecyclerViewAdapter(months_array)
        
    }
}

  • Creates an array of months
  • lateinit: It is used to create properties that can not initialized at first. It says to the compiler that, it will initialize later.
  • Creates adapter reference and passed the array to adapter class that you haven’t create. Don’t worry, if it shows in red color

STEP 5 – Create RecyclerViewAdapter Class

We are going to create RecyclerViewAdapter class which extends RecyclerView.Adapter.

Right-click on Java->New->Kotlin File/Class-> Put the class name as RecyclerViewAdapter and make it the same as the below code.

class RecyclerViewAdapter(var months_array: Array)
{

}

STEP 6 – Create A Custom ViewHolder Class And Extend Adapter Class With RecyclerView.Adapter

In this step, You will create an inner ViewHolder class by extending RecyclerView.ViewHolder. After initializing views in ViewHolder, makes RecyclerViewAdapter extends RecyclerView.Adapter with ViewHolder as the generic parameter. Just like below

class RecyclerViewAdapter(var months_array: Array) : RecyclerView.Adapter()
{

    inner class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView)
  {
      var textview = itemView.textview
  }
}

  • Creates Inner class ViewHolder which extends RecyclerView.ViewHolder
  • Inside viewholder class, initialize row_layout elements. here, TextView.
  • If there is red wavy underline below the RecyclerViewAdapter, then click ALT + ENTER. select implement members
  • select onCreateViewHolder(),onBindViewHolder() and getItemCount() and click OK
class RecyclerViewAdapter(var months_array: Array) : RecyclerView.Adapter()
{
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder 
    {  }

    override fun getItemCount(): Int 
    {   }

    override fun onBindViewHolder(holder: ViewHolder, p1: Int) 
     { }

    inner class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView)
  {
      var textview = itemView.textview
  }
}


STEP 7 – Specify Total Items Using getItemCount() Method

In this step, we will return the array size in getItemCount() method.

    override fun getItemCount(): Int 
    { 
     return months_array.size
    }

  • months_array.length returns 12, JAN to DEC.

    STEP 8 – Create ViewHolder Using onCreateViewHolder() method

    In this step, I will do two important things.
    1. Layout Inflation
    2. Pass it to ViewHolder.

    This is called whenever RecyclerView needs a ViewHolder.

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

    • parent: RecyclerView, viewType: 0, You can have different types of view. Here is only one viewtype, contain value zero.
    • Creates inflater object using context
    • row_layout inflated and become view object
    • Return ViewHolder with view for reference storage purpose

    STEP 9 – Bind ViewHolder With Data In onBindViewHolder()

    Here we will bind our TextView with array item. Access TextView using viewholder. This method calls when the item wants to show, so here we attach data with the view in ViewHolder.

    
    override fun onBindViewHolder(holder: ViewHolder, position: Int)
        {
            holder.textview.text = months_array[position]
        }
    
    
    

    • You can access each element that initialized in ViewHolder class.
    • Here we access textview and set month from string array

    STEP 10 – Set LayoutManager and Adapter

    In this step, You will set LayoutManager and divider, at last, you will attach an adapter too.
    Let’s back to MainActivity. Put the below code in onCreate() and Run.

    
            //sets layoutmanager
            val layoutManager = LinearLayoutManager(this)
            recyclerview.layoutManager = layoutManager
            //sets divider in the list
            val dividerItemDecoration = DividerItemDecoration(this, LinearLayoutManager.VERTICAL)
            recyclerview.addItemDecoration(dividerItemDecoration)
            //Attaches adapter with RecyclerView.
            recyclerview.adapter = adapter
    
    

      • Unlike ListView, We need to implement LayoutManager for RecyclerView. Here we need a Vertical list. Use
      • Make sure you have attached LayoutManger and adapter is not empty, otherwise that may leads to error message
        “e recyclerview no adapter attached skipping layout”

    So use above code and Run

    RecyclerView is ready now.

    STEP 11 – Attach An OnClickListener with Root Element Inside ViewHolder Class

    In this step, you will learn how to get click events and react based on that. Here you will attach OnClickListener with itemView.

                inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
                {
                 var textview = itemView.textview
    
                   init 
                   {
                   itemView.setOnClickListener {
                     Toast.makeText(itemView.context, months_array[adapterPosition],Toast.LENGTH_SHORT).show()
                          }
                   }
    
                 }
            
    

    • init block is called after the constructor
    • Using lambda, Create OnClickListener
    • When item clicks, a toast will appear with Month.
    • getAdapterPosition() method returns the clicked item position, Using Kotlin synthetic property we can use “adapterPositon”here.

    Run again.
    Finally, you have made a simple RecyclerView. Congrats!

    How above RecyclerView Adapter Works?

    how recyclerview works in android

    Okay. let’s clear it out… How RecyclerView adapter works based on the above example?

    • At first, getItemCount() method gets called and that will return 12.
    • After that, for creating ViewHolder, onCreateViewHolder() gets called. It inflates the XML layout and makes View and passes it to ViewHolder for storing references.
    • After that onBindViewHolder() gets called, here we use ViewHolder to access the TextView and attaches text. The 0th row is created.
    • The above process repeats and creates as many ViewHolders to fill the screen and even more. It depends on the screen size and layout size.
    • After that RecyclerView stops calling onCreateViewHolder but onBindViewHolder still repeats its job.

    RecyclerView With CheckBox Example In Android Studio

    recyclerview with checkbox example in android

    In this example, we will create an app that holds CheckBox and its state. While scrolling too.

    Let’s create a project.

    Open your Android Studio.

    Step 1

    Start a new Android Studio project.

    Application Name: RecyclerView With CheckBox In Android Example
    Company Domain: androidride.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.


    After creating the project

    build.gradle(Module.app)

    Add the below code to the dependencies section.

    
    
    //androidx library users
    
        implementation 'androidx.cardview:cardview:1.0.0'
        implementation 'androidx.recyclerview:recyclerview:1.1.0'
    
    /*
    *If you are using the support library
        *implementation 'com.android.support:recyclerview-v7:28.0.0'
        * implementation 'com.android.support:cardview-v7:28.0.0'
        * 
        * */
    
    
    • For Kotlin users, Make sure that you have using kotlin-android-extensions

    activity_main.xml

    
    
    
    
    
    
    
    • It creates a RecyclerView with Vertical scrollbars and assigns id “recyclerview”.
    • If you are using the support library, replace androidx.recyclerview.widget.RecyclerView with android.support.v7.widget.RecyclerView.

    checkbox_row.xml

    
    
    
    
        
    
    
    
    
    • Creates a CheckBox inside a CardView.
    • Support library users – replace androidx.cardview.widget.CardView with android.support.v7.widget.CardView.

    Data.kt

    
    package com.androidride.recyclerviewwithcheckboxinandroidexample
    
    data class Data(var position: Int)
    
    
    • Only one property : position – We can pass it through constructor

    MainActivity.kt

    
    
    class MainActivity : AppCompatActivity()
    {
    
        var list = ArrayList()
    
        lateinit var  adapter : RecyclerViewAdapter
    
        override fun onCreate(savedInstanceState: Bundle?)
        {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            setupdata()
    
            adapter = RecyclerViewAdapter(list)
            //sets layoutmanager
            recyclerview.layoutManager = LinearLayoutManager(this)
            //sets adapter
            recyclerview.adapter = adapter
    
        }
    
        private fun setupdata()
        {
            for(i in 1..30)
            {//creates data object and add it to list.
                var data = Data(i)
    
                list.add(data)
            }
        }
    }
    
    
    

    RecyclerViewAdapter.kt

    
    
    class RecyclerViewAdapter(var list: ArrayList) : RecyclerView.Adapter()
    {
    
        var checkBoxStateArray = SparseBooleanArray()
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder
        {
            val context = parent.context
    //creates inflater
            val inflater = LayoutInflater.from(context)
    //inflates checkbox_row
            val view = inflater.inflate(R.layout.checkbox_row,parent,false)
    //returns ViewHolder with view.
            return ViewHolder(view)
        }
    //returns no of elements, 30
        override fun getItemCount(): Int = list.size
    
        override fun onBindViewHolder(holder: ViewHolder, position: Int)
        {
    
            if(!checkBoxStateArray.get(position,false))
            {//checkbox unchecked.
                holder.checkbox.isChecked = false
            }
            else
            {//checkbox checked
                holder.checkbox.isChecked = true
            }
    //gets position from data object
            var data_position = list.get(position).position
    //sets text with checkbox
            holder.checkbox.text = "CheckBox $data_position"
    
        }
    
        inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
        {//Using Kotlin Android Extensions, access checkbox
            var checkbox = itemView.checkbox
    
            init
            {//called after the constructor.
    
                checkbox.setOnClickListener {
    
                if(!checkBoxStateArray.get(adapterPosition,false))
                {//checkbox checked
                    checkbox.isChecked = true
                 //stores checkbox states and position
                    checkBoxStateArray.put(adapterPosition,true)
                }
                else
                {//checkbox unchecked
                    checkbox.isChecked = false
    //stores checkbox states and position.
                    checkBoxStateArray.put(adapterPosition,false)
                }
    
                }
            }
    
    
        }
    }
    

    • Using Kotlin synthetic properties, we can use adapterPosition for getAdapterPosition()
    • Using SparseBooleanArray, we stores position and boolean value

    Now run the project.

    recyclerview with checkbox in android example - output

    oh, that’s a long tutorial.

    Finally, We are here.

    Guys, Shares really encourage me to create more rich content. Please share this post with your colleagues, family, and friends.

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





    #008577
    #00574B
    #D81B60



strings.xml




    Start New Activity Ex



styles.xml





    
    




activity_main.xml




 	

    

    

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




 	

    



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.