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.
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
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.
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.
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
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.
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.
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
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.
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.
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
<code><code>
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)
}
}
public class RecyclerViewAdapter extends RecyclerView.Adapter
{
String[] months_array;
public RecyclerViewAdapter(String[] months_array)
{
this.months_array = months_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
}
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.row_layout,parent,false);
return new 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()
<code><code>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
public void onBindViewHolder(@NonNull ViewHolder holder, int position)
{
holder.textview.setText(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
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerview.setLayoutManager(linearLayoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this,LinearLayoutManager.VERTICAL);
recyclerview.addItemDecoration(dividerItemDecoration);
recyclerview.setAdapter(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()
}
}
}
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?
<code><code>
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
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
//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
<!--?xml version="1.0" encoding="utf-8"?-->
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
<!--?xml version="1.0" encoding="utf-8"?-->
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
package com.androidride.recyclerviewwithcheckboxinandroidexample;
public class Data
{
int position;
public int getPosition()
{
return position;
}
public void setPosition(int position)
{
this.position = position;
}
}
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)
}
}
}
public class MainActivity extends AppCompatActivity
{
ArrayList dataList = new ArrayList<>();
RecyclerView recyclerview;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupdata();
recyclerview = (RecyclerView)findViewById(R.id.recyclerview);
//pass list to adapter
RecyclerViewAdapter adapter = new RecyclerViewAdapter(dataList);
//sets LinearLayoutManager
recyclerview.setLayoutManager(new LinearLayoutManager(this));
//attach adapter with RecyclerView
recyclerview.setAdapter(adapter);
}
private void setupdata()
{
for(int i=1;i<=30;i++)
{
//creates a Data object and add the position to it.
Data data = new Data();
data.setPosition(i);
dataList.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)
}
}
}
}
}
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.
Let’s learn, how to create an account on genymotion.com and download Genymotion.
How to create an account and download Genymotion?
Step 1
Search “genymotion free” on Google or go to “https://www.genymotion.com/fun-zone/”
Step 2
Click on the button named “Download Genymotion Personal Edition”.
Step 3
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
Fill up the form with valid details.
Step 5
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
Go to your registered email account and click on the link like above.
Step 7
Click on the link “Download Genymotion for personal use“.
Step 8
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.
Then click on the download button based on the operating system.
Download Genymotion virtual devices
Step 9
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
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
Click “install” from the menu.
Step 12
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
Download started.
Step 14
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 to load.
Step 16
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
Open Android Studio, go File->Settings
Step 2
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
Click the install button.
Step 4
Restart Android Studio for changes to take effect.
Step 5
Click on the restart button
Step 6
After the restart, click on the genymotion icon.
Step 7
Choose Virtual devices from the dialog box and click on Start
Step 8
Now click on the run button, genymotion virtual device will be shown on chooser dialog. Select and Click OK.
Step 9
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
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
Genymotion provided with a GAPPS icon to install play store. Click on the icon.
Step 2
Click Accept.
Step 3
Download starts.
Step 4
Click on Restart now, it will redirect to GApps website.
Step 5
That’s all, play store is successfully installed.
Step 6
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
Open genymotion software, on the top-left side, click on genymotion.
Click on settings
Click on ADB
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.
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)
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.
// 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
}
1. Using Strike – Android TextView StrikeThrough XML example
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
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"
textview2.setPaintFlags(textview2.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
textview2.setText("2. StrikeThrough Using Paint Flags");
3.1 SpannableString – TextView StrikeThrough Example
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
SpannableString spannableString=new SpannableString("3.1 StrikeThrough Using SpannableString");
spannableString.setSpan(new StrikethroughSpan(),0,spannableString.length(), 0);
textview3.setText(spannableString);
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
SpannableString spannableString32=new SpannableString("3.2 StrikeThrough Using SpannableString");
//here strikethrough start point: 4, end point: 17
spannableString32.setSpan(new StrikethroughSpan(),4,17, 0);
textview32.setText(spannableString32);
4. Using shape drawable – Android TextView StrikeThrough XML
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
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
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()
// 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
}
String html = "<u>Underline using Html.fromHtml()</u>";
textview.setText(Html.fromHtml(html));
But Html.fromHtml(resource : String) was deprecated in API 24. So now you can use HtmlCompat.fromHtml() method. It’s available in both android.support.v4.text.HtmlCompat, and androidx.core.text.HtmlCompat.
val html = "<u> 1.1 Underline using HtmlCompat.fromHtml()</u>"
//1.1 underline textview using HtmlCompat.fromHtml() method
textview11.text = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY)
String html = "<u> 1.1 Underline using HtmlCompat.fromHtml()</u>";
//underline textview using HtmlCompat.fromHtml() method
textview11.setText(HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY));
1.2 Above underline method in a direct way
This is for beginners. You can directly implement the code just like below.
textview12.text = HtmlCompat.fromHtml("<u>1.2 Underline using HtmlCompat.fromHtml()</u> ", HtmlCompat.FROM_HTML_MODE_LEGACY)
You can underline TextView using SpannableString and setSpan() method with the help of UnderlineSpan().
val content1 = "3.1 Underline using SpannableString"
val spannableString1 = SpannableString(content1)
spannableString1.setSpan(UnderlineSpan(),0,content1.length,0)
textview31.text = spannableString1
String content1 = "3.1 Underline using SpannableString";
SpannableString spannableString1 = new SpannableString(content1);
spannableString1.setSpan(new UnderlineSpan(), 0, content1.length(), 0);
textview31.setText(spannableString1);
3.2 Underline Using SpannableString
You can underline wherever you want in a word or sentence. Just Specify the start and endpoints.
val content2 = "3.2 Underline using SpannableString"
val spannableString2 = SpannableString(content2)
spannableString2.setSpan(UnderlineSpan(),4,13,0)
textview32.text = spannableString2
// 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
}
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1024m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
android.useAndroidX=true
android.enableJetifier=true
strings.xml
<resources>
<string name="app_name">UnderlineTextView Ex</string>
<string name="underline_text">1.3 <u>Underline using HtmlCompat.fromHtml() and string resource</u></string>
</resources>
Sometimes, we make our app using the code from youtube tutorials and blogs and may forget to change the package name at the start. Yes, this happens, most of the time.
We don’t want to display other website name or Youtube channel name to be as our package name, We want a package name that defines us. If you are searching for a tutorial about how to change or rename the Android app package name in Android Studio, then this post is for you.
In this post, I am going to discuss 3 methods that I am using and still working.
Method 2 – How to change full package name of project by creating new package
In this method, We are going to change package name “com.androidride.myapplication” to “info.xyz.yourapplication”
STEP 1
Right click on com.androidride.myapplication package and select Refactor->Move
STEP 2
Choose Move package “com.androidride.myapplication” to another package and click on OK.
STEP 3
Now you will get a warning dialog shows Multiple directories correspond to package com.androidride.myapplication
Click on Yes
STEP 4
Enter the new package name except the last level, For example. If you want to make package name as “info.xyz.yourapplication” then type “info.xyz” only, like above. Avoid the last part, here “yourapplication”.
STEP 5
Click YES for creating new package.
STEP 6
Click on Do Refactor. Now package name “com.androidride.myapplication” changes into “info.xyz.myapplication“.
STEP 7
Now we have to change the last package level name,
Right click on package name -> Refactor -> Rename
STEP 8
Click on Rename package
STEP 9
Rename “myapplication” in to “yourapplication”.
STEP 10
Click on “Do Refactor”
STEP 11
Use CTRL key and select each package related to old package name and delete. You can use DELETE key in keyboard or right click after selecting old packages and click on delete option from the menu.
STEP 12
Open build.gradle file, change applicationId and Click on sync now.
Package name successfully changed to “info.xyz.yourapplication“.
Method III – How to rename android app package name in Android Studio using existing package
This method is also same as the second method. Just like second, we change package name “com.androidride.myapplication” to “info.xyz.yourapplication“.
STEP 1
Right click on Java and select New -> Package
STEP 2
Next dialog box appears, choose …app\src\main\java as Destination Directory.
STEP 3
Enter your package name, here info.xyz.yourapplication
STEP 4
Now move old package files into new package. Here move files from “com.androidride.myapplication” to “info.xyz.yourapplication“. Just use CTRL key to select all files and drag it to new package.
Files moved.
STEP 5
Open AndroidManifest.xml and change package name into “info.xyz.yourapplication“
.
STEP 6
Open build.gradle (Module: app) file, change applicationId also. Change it to “info.xyz.yourapplication” and Click on Sync now.Now you might get errors. It is due to the R file import. There are two scenarios, we can do.
Remove R file import line from both files and check the error still exists. If not then you can delete old package files now
It’s done. You have successfully changed the package name.
Otherwise, If the error still exists, do the below steps.
STEP 7
Select R file import line just like above and press CTRL + SHIFT + R . Replace with new package name. Click on replace all.
STEP 8
Click on replace
STEP 9
Delete old package and related files
STEP 10
Build->Rebuild
Yes, the package name is changed.
Express your thoughts below and tell your friends about this post. Thank you.
Click Shift key twice or search icon at the top – right side corner of the Android Studio
Search “plugins“
Click on plugins item on the list
You can also get plugins window by File->Settings->Plugins
Now plugins window will appear, just click on “Browse repositories“
Search “Android Wifi ADB” plugin”
Select “Android WiFi ADB” from plugins list”
Install it.
The plugin will be downloaded.
Click “Restart Android Studio“.
Android Studio shows a notification Restart Android Studio to activate changes in plugins? Click “Yes“
Make sure that USB debugging is fine and successfully connected with the USB cable.
After the restart, just click the Android WiFi ADB icon that besides the run button like above.
Android Studio notifies with a message that your device is connected.
Disconnect your device, otherwise run dialog will show your device twice. one as USB device, other as WiFi device.
Click the run button and select your device in the run device dialog.
After selecting the device, it will continue to download through WiFi and install on your device.
Strategy NO:2 – How to run your app over WiFi using ADB commands
Sometimes, This method may difficult for you if you are a beginner. But we are just
connecting the device using the IP address
Install the app through ADB command.
Open Android Studio,
Click your terminal on Android Studio, You can also use the command prompt.
Type “adb devices” and Press Enter key – List the devices which are connected to system.
If your device is plugged with USB, then it will show it to you on the terminal.
Type “adb tcpip 5555” and Press Enter key.
Now you can disconnect your device.
Find the IP address of your smart device. You can find it by Settings-> About Phone -> Status -> IP address.
Now connect your device over wifi by running
“adb connect <IP address of your Android Device>:5555“
that’s all. your Android device successfully connected with computer.
Install apk – adb install “full location of apk”
adb install C:/app-debug.apk – here C:/app-debug.apk – full location of APK, I just placed the APK to C drive.
It’s a nice technique, but we are not saying that to leave USB cables forever. It’s needed for initial setup. If your pc and Android device restart again, Then you need to use USB cables again for reidentify the device.
Share your experiences with us and don’t forget to share.
In this example, you will learn how to open the calendar on button click in Android with an example. Here I use DatePickerDialog, not CalendarView. Beginners tend to use Calendar, that’s why I use that here.
//getting current day,month and year.
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
Calendar calendar = Calendar.getInstance();
int year=calendar.get(Calendar.YEAR);
int month=calendar.get(Calendar.MONTH);
int day=calendar.get(Calendar.DAY_OF_MONTH);
3. Initialize DatePickerDialog with the current date and show it. If you don’t and use 0 as day, month, and year. Then DatePickerDialog shows Feb month 1900.
DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener()
{
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)
{
}
}, myear, mMonth, mDay);
datePickerDialog.show();
4. Get day, month and year from DatePickerDialog onDateSet() method.
When you select a date in DatePickerDialog, onDateSet() method gives day, year in the as correct number specified in DatePickerDialog. But month value varies from 0 to 11. So just add 1 to month value to show the original month number.
Create Project – Open Calendar on Button click in Android Example
Let’s create a project that sets the date in EditText. When you click on Button, DatePickerDialog shows up, When you select a date, it sets on EditText.
Start a new Android Studio project
Application name: Open Calendar on Button Click in Android Example.
Conclusion
There are many occasions when you need a date from the user. Date of birth in sign up process, Ticket reservation, and date of an upcoming event just like that. It may not be user-friendly If the user needs to type it down. Android provides views for that, so users can easily pick it up. So I think if you are making an app like that, this post might have helped you. If you like this tutorial, please share it.
In this tutorial, you’ll learn four ways to make an Android TextView bold. You can easily adapt the code and use it in your project as needed. Let’s get started!
String html="This is TEXTVIEW 3";
textview3.setText(Html.fromHtml(html));
Html.fromHtml(String source) was deprecated in API level 24. Use androidx.core.text.HtmlCompat instead. For using HtmlCompat, you need to include dependency in your project.
implementation 'androidx.core:core:1.0.1'
If you got Manifest merger failed error, then add below code in gradle.properties.
String html="This is TEXTVIEW 3";
textview3.setText(HtmlCompat.fromHtml(html,Typeface.BOLD));
HtmlCompat.FROM_HTML_MODE_LEGACY – It just adds two newline character between block level elements.
Way 4 – Make Android TextView Bold using separate style
In this example, we create a separate style resource and set it to our TextView. The advantage of this technique – you can use this style for many TextViews. Just specifying style attribute.
Step 1
Create a separate style resource named “boldStyle”, add “android:textStyle” as item and provide value “bold”.
Step 2
Set style to TextView using style attribute.
Let’s create an Android app with these examples. Open your Android Studio,
// 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
}
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1024m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
android.useAndroidX=true
android.enableJetifier=true
colors.xml
#008577#00574B#D81B60
strings.xml
TextView Bold Example
styles.xml
activity_main.xml
MainActivity.kt
package com.example.androidride.textviewbold_kotlin
import android.graphics.Typeface
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.text.HtmlCompat
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Make textview bold - programmatically
textview2.setTypeface(null,Typeface.BOLD)
textview2.text= "TEXTVIEW 2"
//Using fromHtml() method
val html = "This is TEXTVIEW 3"
textview3.text = HtmlCompat.fromHtml(html,HtmlCompat.FROM_HTML_MODE_LEGACY)
}
}