how to install or add kotlin plugin in android studio
Finally, Google has accepted Kotlin as the official language for Android app development. This doesn’t mean we have to stop making apps using JAVA. You can, but Kotlin makes the process more simple and efficient.
These are some points I want to discuss with you about Kotlin,
Interoperable – It is based on JVM. So you can use Kotlin wherever you use JAVA
Concise – It is easy to read, write, maintain and need less code when compared with JAVA
Kotlin supports Object-Oriented Programming and Functional Programming
Code is safe – You can say goodbye to NullPointerException. If you assign a null value to an object reference, It will easily found at compile time. But you can assign a null value to a variable by explicitly adding “?” (Question mark) after the data type
reduces boilerplate code –
No more findViewById() calls – Kotlin Extensions plugin helps us to access UI widgets using id.
No need to type data class’s setter ,getter, and toString() like methods (functions in Kotlin). Kotlin compiler will automatically generates these methods.
There is no need for the semi-colon, Actually Kotlin allows it. But does not force it.
Do you think It’s better to start making apps with Kotlin ?. Then we will help you to complete the First step.
Yes, installing the Kotlin plugin in Android Studio.
After installation, Android Studio able to achieve Kotlin code compilation, execution, Unit Testing, and debugging.
You can also convert Java code to Kotlin in a single click. Click below link to find out
If you are using Android Studio 3.0 and above just like me, you don’t need to worry about Kotlin plugin. That’s already set for you. You can create a Kotlin project from now.
If you are using android studio 2.3 or below, you need to perform below steps to work with Kotlin.
Let’s launch Android Studio.
If you are already opened a project, select File-> close project to land welcome page of Android studio.
Click on configure button and select plugins option.
Click Install JetBrains plugin button
1. Search “Kotlin” without quotes or you can scroll down the list and find Kotlin.
2. Click on Kotlin plugin item
3. On the right section of the window, click on the Install button.
Download starts…
After a short time, when download completes. Install button becomes “Restart Android Studio“. Click on that.
Next dialog box appears. Click Restart to activate changes in plugins.
From now, Android Studio is fully compatible with Kotlin.
While creating a project, Check Include Kotlin support, then all are as usual.
Conclusion
One of the simple language Kotlin finally added to Android Development world. Kotlin has lots of advantages over Java. That will ease your development process, at the same time you can make the app more efficient. You can easily start building Android apps in Android Studio by just installing the Kotlin plugin. Since Android Studio 3.0, You don’t need to install it, they come with inbuilt support. Even though Kotlin does not have resources for learning like Java. But it will benefit in the long run. That’s all. Thanks for scrolling… Please share it.
Have you ever seen “touch again to exit” or any other white text in a black capsule shape as pop up in Android???
Those popup messages are toast. In this post, you will learn about it with a simple Android toast example.
Okay… what is toast in Android???
Toast is the subclass of java.lang.Object class, and it helps developers to make notification message that appears at the bottom of the screen by default. The temporary message pops up and fades away after a short time. Just like hot bread pop up from a toaster. While showing toast you can still access your activity.
Okay…Let’s make a toast in android
How to make toast in Android?
You can make toast in 2 simple steps.
Call static method makeText() of Toast class and give
Context
CharSequence or String resource id
Int duration : LENGTH_LONG or LENGTH_SHORT
Call show() method
Toast toast=Toast.makeText(getApplicationContext(),"Yeah!... I am Toast",Toast.LENGTH_LONG);
toast.show();
Make a toast in one statement.
Toast.makeText(getApplicationContext,"Yeah!... I am Toast",Toast.LENGTH_LONG).show();
Don’t forget to add the show() method, because it happens sometimes for me and thinks why the code doesn’t work after a long stare at the bottom of the screen.
You can make toast in the background services. if your application not in the foreground while toast showing up, Toast may confuse the users. So use appropriate text with the toast to assist users to digest easily.
When you call makeText with your parameter value. Internally, it inflates $YOUR_SDK$/platforms/android-22/data/res/layout/transient_notification.xml and set your content to textview which have id message.
android-22 is API level, It may change based on your SDK.
LENGTH_LONG: It shows view or toast for almost 3.5 seconds.
LENGTH_SHORT: It shows view or toast for almost 2 seconds.
Public constructor
Toast(Context context)
It creates a Toast object.
Public methods
i) public void cancel()
It hides the toast if it is already showing or if it isn’t visible yet.
ii) public int getDuration()
It returns the duration of view or toast. (LENGTH_LONG or LENGTH_SHORT)
iii) public void getGravity()
It returns location if that is already set.
iv) public float getHorizontalMargin()
it returns the horizontal margin in float value.
v) public float getVerticalMargin()
it returns the vertical margin in float value.
vi) public View getView()
It returns the view. You can access view items using this method.
vii) public int getXOffset() && public int getYOffset()
It returns X offset and Y offset in Pixels.
viii) public void setDuration(int duration)
Use this method to set the duration of your toast or view.
ix) public void setMargin(float horizontal_margin, float vertical_margin)
Use this method to set margins of your view or toast. actually here margin means how much space needed between toast and side of the screen.
x) public void setText(int Resource_id or CharSequence string)
There are two variations of setText(…) method. One receives parameter as charSequence and other receives as string resource id. You can update the text in the toast that previously you create with makeText() method.
xi) public void setView(View view)
It sets the view for toast. It’s helpful while creating a custom view.
xii) public void show()
It shows the toast or view.
Create a project – Android Toast Example
In this project, we will make a button inside LinearLayout. When the button is tapped, a toast will appear at the center of the screen with application name in it.
File->New->New Project
Application name: Toast Ex
company domain: androidride.com
click Next and select your minimum SDK and empty activity template.
Here, makeText() method returns a toast object and Using toast instance setGravity() method position toast at the center of the screen and show() method helps to display the toast.
In this post, you will learn about the Android Support Library and How to add in your Android Studio project.
In Android app development, support libraries have an important role. Without them, It might difficult to provide a consistent look and feel in all devices.
Okay, tell me in detail.
What is Android support library?
There are many devices still running in Jelly bean and below versions. So you need to give the same importance for old and new devices While making an app. Otherwise, the App in old devices looks dull when compared to new ones.
That may affect the app’s market. To avoid this trouble, Android introduced the Support library. These are set of code libraries that provide backward compatibility and you can find it on Android SDK. These libraries experiences revisions for fresh features and bug fixes. Package name shows which Android Version it supports from.
For example : android.support.v7.app.AppCompatActivity – It can be used with API level 7 and higher.
After the release of support-library 26.0.0, support for minimum API level change it to API level 14 . So Don’t confuse with v* notation
The Android Support library includes
Palette – It used to take out colors from image.
CardView – Provides card look like widget.
leanback – Helps to make UI for TV apps.
Mediarouter – Supports for Media Routes.
gridLayout – Arranges widgets in grid manner.
RecyclerView – New version of ListView and GridView.
AppCompat – Provides support for ActionBars.
support-v4 library – User Interface features and other components.
MultiDex – helps to make apk contains multiple dex files.
RenderScript – Enables latest features of RenderScript .
Annotations – improves code .
If you are a beginner and experimenting with online tutorials, there may be a chance to edit the gradle file directly for adding the library as a dependency, sometimes wait for a download too.
Before doing that you can perform the following procedures to find and add an available version of the same support library. You can use this way to add AppCompat, Design, CardView, RecyclerView and so on.
There are two methods you are going to learn here. First one is simple and fast. The second method is an old one. But it’s good to know about that.
We assume that you have opened Android Studio and your project.
Method 1 – How to add support library in Android Studio
Open build.gradle(Module:app) file
Use ALT + ENTER and select Add library dependency
.
Select from the list, Here I am adding CardView.
CardView is added to my project. Just like this, you can add any library. If there is a sync needed. Just sync it.
Method 2 – How to add support libray in Android Studio
File->Project Structure you can use “Ctrl + Alt + Shift + S ” key combinations.
click the app module.
Click the Dependencies tab, you will see already added libraries below. click the + Button shown in the Right side of the window.
Choose library dependency from available options.
Choose library dependency dialog will be visible now. You can search here or choose the desired library that you want from the list. After your selection, just click OK.
The selected library will be added as a dependency in your dependencies tab list and click OK.
Just look at the build.gradle(Module: app) file dependency section, Android Studio will add your selected library. Please share it and your valuable comments will help us to improve.
Conclusion
The Android Support library helps to reduce the headache of developers by providing backward compatibility. Users also feel fresh and happy with their old device. There is no complexity in adding support library in Android Studio. You can do it in simple steps. I assume the above words might have helped you.
In this post, you will learn how to perform an action using Button and onClick attribute in XML. It is simple and easy to understand. Before creating the project, Let’s know more about android:onClick attribute in Android.
How android:onClick XML attribute works here with Button?
For detecting tap or button click event in android we can use android:onClick attribute. When users tap the views which hold android:onClick , android looks for the method in the activity. If the exact method found, that will start execution. So, provide a valid method name that lives in hosted activity as the XML attribute value. Not only Button It works for ImageButton, CheckBox, and RadioButton too.
Let’s create a project, In this project, we will add a Button and TextView, When the user taps the Button it calls a method in the activity depends on android:onClick value and set text in TextView.
Next screen prompt for making an activity class file and its layout.
Activity Name: MainActivity
Tick the generate the layout checkbox if it’s not checked.
Layout Name: activity_main
Tick Backward Compatibility checkbox and Click finish.
Step 5
open activity_main.xml and paste the below code
You can drag LinearLayout, Button, and TextView wherever you want and give id, onClick attribute as you want or you can simply paste the below code. The layout just contains the Button and TextView inside LinearLayout.
Now you can see android:onClick value (myMethod) is underlined with red color and gives you an error message that “Corresponding method handler ‘public void myMethod(android.view.View) not found.
This is because we didn’t define the method in our MainActivity class.
Step 6
Define myMethod and set text
Obeying all rules specified earlier, create myMethod() and initialize and set the text to textview.
package com.androidride.buttononclickex;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void myMethod(View view)
{
//get the textview
TextView textView=(TextView)findViewById(R.id.textview);
//set text to textview
textView.setText("Button clicked");
}
}
In this post, you will learn how to create another activity in Android Studio.
When you started the Android Development journey by creating Hello World or any other app. You just filled your First Activity form. But now you want to make another activity, but you don’t know what to do?
Then don’t worry I will help you.
Okay… Actually What is Activity??
In short, Activity is what we have seen in Android apps with the user interface.
Okay, Let’s create a new activity. I assume that you already opened Android Studio and a project.
Step 1 – How to create another Activity in Android Studio
Right click on project package (here com.androidride.createactivity3) in App-> Java. and select New -> Activity -> Empty Activity/Blank activity.
First of all, make sure you are in the Android view in the project explorer. Some views don’t have new activity option. If you are in other views, Just click on the downward arrow and choose Android from the given options.
It’s not a problem if you don’t see Empty Activity option. In older versions of Android studio, you might find Blank activity option. Both of them are the same just a name difference. Don’t use Basic activity now because that’s the advanced version of Empty Activity/Blank activity and contains Floating action button.
Enter your activity name, at the same time layout layout name automatically fills up for you if Generate layout file checkbox is checked.
Then Backwards compatibility(AppCompat) option will give the app a certain look in almost all devices, at the same time your activity will extend AppCompatActivity class. For a beginner like you, you can leave the option as empty that cause your activity to extend Activity class and Click Finish.
Your activity files are created. congrats…
You can also create another activity in the Android Studio using the File menu option.
One of the main building blocks of the Android app is activity. Activity is a class in Android SDK, at the same time it’s just a screen with the user interface of our app. Creating another activity in Android Studio is really simple. If you are a beginner or comes from eclipse, you can easily make a new activity without confusing through the above steps. I think this post might have helped you. If you found anything useful, please share it.
And at last,leads to Application not responding (ANR) dialog ???
Why is this happening?
As a matter of fact, Your application performs a too much intensive task on UI thread, at the same time it takes time to complete. For the sake of user convenience, the Android system will show you ANR dialog and stop your app forcefully.
In more detail, When the app gets started execution, Main thread or UI thread gets created. By default, all lifecycle methods like onCreate(,onStart(), and onClick, UI update works are serially done by UI thread. But When app developer put complex operations like
Network operations.
Disk I/O tasks.
Database Queries.
Other CPU intensive actions.
The app needs more time to perform. So at that time UI thread can’t update or repaint user interface. App freezes, operations exceeds the definite time fixed by the Android system. finally, the system decides to kill the application to make the device available to the user for other acts.
For making a neat and smart app, you should avoid all complex scenarios performing on UI thread.
Then what to do??
Where do we put our code to gets executed ??
You can use threads.
While performing these operations, You should notify the user through UI that something is happening behind. Otherwise, the user doesn’t know what is happening in your app. But you can’t perform any UI updations from your threads, that job is done by one and only Main Thread or UI thread. Then how could we use the main thread to notify the user?
Hello, is there any solution?
Yes, For beginners, use AsyncTask.
What ??
AsyncTask.
Full name, please??
Android.os.AsyncTask
nice name.. Carry on.
AsyncTask is just like a side road, while large-slowly moving truck makes traffic problem on the main road, Asynctask keeps those away to make a better path for other traffic.
For beginners, It’s the first and one of the best option for performing difficult work.
AsyncTask name came from the asynchronous task. It is an abstract class and you can find it on Android SDK. It helps Android app developers to execute operations like
Downloading and uploading files like JSON, XML, images, and small size other files.
.
You can’t perform network operations on main thread since Honeycomb – API level 11. The system will throw android.os.NetworkOnMainThreadException. However, you must use AsyncTask or threads to perform network tasks.
Storing and reading data from large text files.
All Database CRUD(create,read,update,delete) operations.
Other CPU intensive operations.
In background or worker thread. Same time helps to update UI on UI thread. Asynctask makes use of UI thread in a better manner.
It eases the tension of developers from
Thread creation and termination.
UI thread synchronization and management.
How to use AsyncTask in your project
In this part, I will explain in more detail.
First of all, If you
do not know how much time needed for your task or task takes a long time
Want to perform an infinite loop work
AsyncTask is not a better option for you. AsyncTask mostly used for short operations(a few seconds at the most)
To make AsyncTask do work, we want to do 3 most important things.
1)Create a subclass of AsyncTask
2)Override doInBackground() and other methods.
3) Make an instance of AsyncTask subclass & call execute().
1)Create a subclass of AsyncTask
For performing different types of data operations, AsyncTask uses generics. So while making a subclass of AsyncTask, you must specify 3 generic data types.
Params, Progress, Result
1)Params: data used to start background thread execution.
For example, AsyncTask downloading an image file using URL, then specify URL as params.
2) Progress: data that used to notify progress of the task.
While downloading an image, You want to show the user how much percentage of the image has been downloaded. So you can use Integer as Progress.
3)Result : data that return from doInBackground() after execution.
For the same image downloading example, you can use Bitmap if doInBackground() code returns an image.
e.g:
Class Subclass_Name extends Asynctask
In real,
Class MyTask extends AsyncTask
What if you do not want to
Pass parameters to doInBackground()?
Show progress to the user?
Return any result?
You can use Void data type just like other.
Class MyTask extends AsyncTask
Do not use primitive data types as parameters.
Class MyTask extends AsyncTask
This is wrong.
2) Override doInBackground() and other methods
onPreExecute()
Optional. It calls before task executes on the background thread and you can use it to set up a task. It runs on UI thread, so you can access UI elements here. In most cases, the app performs the animation or set visible ProgressBar or ProgressDialog.
doInbackground(Params… params)
Most important method in AsyncTask, After the successful completion of onPreExecute() it leads to doInBackground(). It does all intensive tasks in the background thread. It receives parameters as var args. Varargs means a variable number of arguments(like an array of elements), it can receive a number of parameters. You can access each element using an index just like the array.
.
While performing a repetitive task, you can publish it progresses through onProgressUpdate using publishProgress(). Which data type returns from doInBackground(), that type must be the parameter of onPostExecute().
If you use AsyncTask only for implementing doInBackground(), Use java threads.
publishProgress()
This method is used to connect and pass data from doInbackground() to onProgressUpdate(). Just like a bridge.
onProgressUpdate(Progress… progress)
Optional. It also uses varargs as parameters. It runs on UI thread, so you can use this method to notify task’s progress.
For example. If your app downloading lots of images. There may be a chance to user gets bored. So you can publish each photo to the user through onProgressUpdate(). That must be a great relief to the user.
The progress won’t directly be published on Main Thread. It uses handler internally bound to Main thread looper for execution. If there is lots of work in the Main Thread, progress will not update smoothly.
onPostExecute(Result result)
This is also optional and runs on the Main thread. It’s the most used second method in Asynctask. After successful completion of doInBackground, onpostExecute() starts with result from doInBackground. In some cases, this method uses to stop animation or hide progress bar that you started in onPreExecute().
onCancelled(Result result)
Optional and runs on the Main thread. It invokes only when the cancel() method is called with the instance of AsyncTask subclass. It will not invoke if doInBackground completes. After its completion, it will assign control to onCancelled() with no parameters. Override onCancelled() when nothing returns from doInBackground(). Use this to avoid checking data is null or not.
You can make different UI appearance for successful and fail completion by using onPostExecute() and onCancelled().
Note: Do not call these methods manually, you can. But don’t.
These methods are callbacks except publishProgress, they will invoke automatically by the system at an appropriate time.
3)Make an instance of AsyncTask subclass & call execute()
Android provides 2 methods to start AsyncTask.
1) execute (Params… params)
2) executeOnExecutor (Executor exec, Params… params), added in API level 11.
Call these methods using an instance of the AsyncTask subclass. doInBackground get their parameter data from these methods.
When AsyncTask added at first, execute method preferred serial execution. Later, means API level 4 android engineers change their decision to execute in parallel and it continues to level 12. With the introduction of executeOnExecutor() at API level 11, they give concurrency control to the developer. The app developer can decide how to execute our task in serial or parallel.
Two Executor parameter determines concurrency:
1.SERIAL_EXECUTOR: This executor parameter uses for performing a serial execution, they start each task after completing one by one. They promise that each task will complete in the order they were started or added. Just like a Queue.
2.THREAD_POOL_EXECUTOR: You can pass this executor object to perform a parallel execution, they do not give you any guarantee to complete the task in the order they were started. Asynctask will start as soon as possible when they get a thread from the thread pool
Note: execute() must be invoked on the UI thread and task instance must be created on UI thread
Just like threads, AsyncTask executes only once. If you try to execute more than once with the same reference to AsyncTask subclass you will end with an exception with message Cannot execute task: the task has already been executed (a task can be executed only once)
If you try to execute the same task with the same reference to AsyncTask subclass while it running another exception will be thrown with the message “ Cannot execute task: the task is already running.
If you want to execute the same AsyncTask more than once, just create a new instance and call execute.
new MyTask().execute();
How to cancel AsyncTask
What if the user selected a wrong option and want to cancel a running task?
AsyncTask provides a better cancellation strategy, to terminate currently running task.
cancel(boolean mayInterruptIfitRunning)
myTask.cancel(false)- It makes isCancelled returns true. Helps to cancel the task.
myTask.cancel(true) – It also makes isCancelled() returns true, interrupt the background thread and relieves resources .
It is considered as an arrogant way, If there is any thread.sleep() method performing in the background thread, cancel(true) will interrupt background thread at that time. But cancel(false) will wait for it and cancel task when that method completes.
If you invoke cancel() and doInBackground() hasn’t begun execute yet. onCancelled() will invoke.
After invoking cancel(…) you should check value returned by isCancelled() on doInbackground() periodically. just like shown below.
protected Object doInBackground(Params… params) {
while (condition)
{
...
if (isCancelled())
break;
}
return null;
}
AsyncTask’s Status
Asynctask tells their current state by giving below status.
1. PENDING: In this state, AsyncTask is not started, execute or executeOnExecutor() is not invoked. But you have created an AsyncTask instance.
2. RUNNING: Asynctask started their job, it will remain in this state from onPreExecute to onPostExecute or onCancelled.
3. FINISHED : This state will set when onPostExecute() or onCancelled() is completed.
you can check these statuses by calling getStatus() method using asynctask instance.
Android AsyncTask Example
Let’s make an application and familiar with Asynctask.
Does your Android Studio takes a lot of time to build and run??
If you have a low-end pc, then this time increases.
When I hit the run button, I sit and wait for gradle to get finished. One minute is gone, two minutes, three minutes.
In my old PC, Waiting has passed more than 30 minutes.
That affected my productivity very badly.
End of the day, I feel miserable, nothing is done, Still waiting for gradle build completion.
At that time, Just like any other beginner, I searched on Google “How to reduce Android build time”. But nothing gets worked.
Then I learned about the Gradle build system. after that, I got to know we can run the project using Commands.
So in this post, I will tell you a way that I am using which reduced my APK build time.
Yes, this is really interesting and It will be useful in the long run.
Before that, let’s make a simple talk about Gradle and gradlew.
What is gradle and gradlew??
Gradle is a build tool which makes APK using our source code and resources like layouts, images by giving them to suitable tools. When you click the run button, Android Studio delegates power to gradle and wait for it to finish just like us.
gradlew is a batch file in Windows. In Mac and Linux, it available in the form of a shell. You could find it on the Android Studio project’s root directory. It has the ability to pass commands to gradle. Using those commands we can make Gradle work. gradlew is also responsible for downloading gradle from the Internet.
If you are in the Android Studio project folder, Open your command prompt and Just type gradlew and press enter. The script runs and looking for a gradle in your system. If the desired one not found, It goes online and downloads gradle.
Everybody hates to be waited, there no change in build time too. Build takes so much time from our life and it increases the development period. High-level PC and gradlew installdebug command can help you to save your valuable time. Using gradlew and Gradle we can do so much stuff. If there is any other technique you use. Feel free to comment here and please share this article. Thank you, guys.
These methods are available from API level 1. Let’s talk more about these types.
setContentView(int resourceId)
This method uses layout constant from automatically generated R.java class. R.java class holds many static constant values in nested classes. So that you can access directly by specifying R class and nested class.
Nested Layout class contains layout resource constants to ease the availability of actual files in the resource directory.
At runtime, the System will select the appropriate layout based on orientation and other factors like language and region. By default, it selects the layout in the res/layout directory.
Eg:
setContentView(R.layout.activity_main);
Here, R.layout.activity_main is an integer value contained inside of the layout class in the R.java file. Using this integer value Android system will look in the res/layout directory. That’s how android finds the correct layout.
If you are using XML layout do not try to initialize views before calling setContentView(R.layout.layout_name), because without inflating the layouts, there are no actual views in memory. It will lead to NullpointerException.
Set any view as your activity’s content. View’s height and width set to MATCH_PARENT as default.
@Override
Protected void onCreate(Bundle savedInstanceState)
{
//create a textview object
TextView textview=new TextView(this);
//set text to textview
Textview.setText(”hello world!”);
SetContentView(textview);
}
You probably need to add an import android.widget.TextView; statement.
setContentView(View view, ViewGroup.Layoutparams)
Extension of setContentView(View view) method. Here you can specify view’s parameters.
@Override
Protected void onCreate(Bundle savedInstanceState)
{
//create a LinearLayout object
LinearLayout linearLayout = new LinearLayout(this);
//set orientation
LinearLayout.setOrientation(LinearLayout.HORIZONTAL);
//make LinearLayoutParams object with width as MATCH_PARENT and height as MATCH_PARENT
LayoutParams linearLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
SetContentView(linearLayout,linearLayoutParam);
}
You can add child views to Linearlayout using addView() method.
You can call many times setContentView() method, but it works only at the last call.
You can use setContentView() outside of the onCreate() method.
ListActivity does not use setContentView() Because it already contains a listview and use setListAdapter() to populate.
In fragments, LayoutInflater does layout rendering work with inflate() method. Just equivalent to setContentView().
Sometimes, you need to display a layout from many layouts based on any condition. Like showing login or signup page. So there is no need to create two activities. Just use if statement or other depends on your needs and do just like below.
That’s all for now. Is there any suggestions, please comment below.
Conclusion
One of the most known methods in Android is setContentView(). I think most of us started Android development by thinking about what is setContentView and what it does. It’s used to show the app’s appearance. We can show our UI effectively by programmatically or using XML layouts. Android uses a different approach to showing XML layouts. Sometimes, it may difficult for beginners to understand. But I think, I have explained well by picture. If you have any doubts feel free to ask. By the way, sharing is caring.
Then you must learn basics well, better you understand the fundamentals, easier to learn the advanced concepts.
So today I am talking about Android layout, the word you already heard and a basic concept.
So let’s start here,
What is Android layout?
In Android, the layout describes the appearance of the app. Layouts are just resourced files. The instructions or content in layout decides to position your widget and make your user interface.
The layout contains View, ViewGroup objects and <merge> tag. Just like HTML, It must have a root element. It can contain more GUI widgets like Button, TextView, etc. Nested elements are also supported.
An app can have more than one screens based on developer needs. So you can have many layouts as you want.
Layout resource names must contain only lowercase a-z, 0-9, or underscore otherwise, you might end with an error.
Different types of Android layouts
For user convenience, Android engineers developed many layouts.
LinearLayout – Arrange Android widgets vertically or horizontally.
RelativeLayout – Organize widgets relative to each other.
You can use XML straightforward vocabulary to specify your UI. For beginners, you can check it out drag and drop feature. It helps us to drag a view which you want and drop it wherever you want in layout design. The XML code will automatically complete by android studio.
For localization (translating strings into different languages), XML layout would be a better idea.
Note: You must put xmlns:android attribute with android namespace inside the root element.
For an example: assume LinearLayout as your root element.
How to create Android layout Programmatically at runtime
It’s not generally recommended for beginners. There may be occasions to make your layout at runtime. But it mixes up UI code and code that controlling app behavior. So it may become difficult to tweak and refine user interface.
Where is layout files located at?
Android studio automatically creates a directory to hold your layout files – layout subdirectory.
In your project structure
app->res->layout .
all resource files stored in res (resources folder).
How to create a layout file in android studio?
Right Click on your default layout subdirectory
New -> Layout resource file -> Enter layout Name and click OK.
Also give details of the root element, source set, Directory name, and other available qualifiers.
How to rename layout file in android studio?
Right click on your layout file which wants to rename
Refactor -> Rename -> give new file name -> Refactor. You can use shift + F6 key also.
Conclusion
There are some set of words may confuse developers when they start Android apps Development. One of them I think is layout. Better you learn each term in any language, better programmer you will be. In this post, you learned about layout. The layout defines the appearance of the app or It says how should User Interface elements get arranged. You can define layout in an easy and difficult way, Through XML and programmatically. There are different types of layouts, using them you can accomplish an awesome user interface. If you got anything useful, please share it.
Those messages in the listview are sent by my crush to me.
Yes, that was the best dream I ever had ;-).
I’m just kidding…
Let’s back to the topic,
When beginners make an app for showing a collection of data, Most of them prefer ListView. It is easy to work with listview when comparing its successor RecyclerView. Although ListView becomes old now, the uses of ListView still goes on.
You don’t need to code the adapter to make ListView. Android API already provides an easy way to build a listview.
In this tutorial you will learn to construct listview easily and less code.
The android:entries XML attribute helps us achieve our target.
Easy to populate ListView, Spinner, Gallery and ListPreference.
Only static, unchanging string data allowed. So you can’t use with data from internet, database,
shared preferences etc.
How android:entries works ??
pin me …. too
As shown in the picture, android:entries attribute needs an array resource name, not the file name which contains array resource. You can define the array resource in strings.xml. Not only listview, Spinner, ListPreference, and gallery also use android:entries attribute. But gallery deprecated in API level 16. As a successor of ListView, RecyclerView doesn’t hold entries attribute.
When the user runs the app, the Listview constructor takes the array resource referred in the entries attribute. Then the constructor makes an adapter itself with the simple_list_item_1 layout in SDK. Then assign it to the ListView.
Actually, we just point our data to the ListView, listview does all other work.
This is the way how it works.
How To Make A ListView In Android Studio
Step 1
Create a new project
In Android Studio, create a new project File -> New -> Project
Application Name: Simple ListView Ex
Company Domain: androidride.com
Android convention to use the reverse of the domain name. that’s never a problem for you.
Click Next
Step 2
Choose your minimum SDK
It is necessary to choose the minimum SDK that you want. tick the phone and tablet checkbox for making the app for only phone and tablet.
Click next
Step 3
Select empty activity template
For this project, we just need an empty activity. So just select the empty activity template and click next.
Step 4
Create a new empty activity and layout
Next screen prompt for making an activity class file and its layout.
Activity Name : MainActivity
Tick the generate the layout checkbox if it’s not checked. Click finish. Now, you will see the MainActivity class
Step 5
Change toolbar and status bar color
You can skip this step if you don’t want to alter the default style. Open res/values/colors.xml and paste the code below to make a red colored toolbar.
#f82900
#bc0000
#f82900
Step 6
Make a string array to hold the contents of the listview.
Open res/values/Strings.xml, and paste the below code between .
Hi
Helloo
How are you
Heyy
Why didn\'t you reply to me??
Use escape sequence \’ to get the apostrophe in the last string.
Step 6
Add android: entries attribute and its value in listview XML definition.
open res/layout/activity_main.xml, delete the existing code and paste the code below.
<!--?xml version="1.0" encoding="utf-8"?-->
If you wish to add other widgets to your layout, then you can add ViewGroups like RelativeLayout, LinearLayout and other. Then just replace the XML namespace ( xmlns:android=”http://schemas.android.com/apk/res/android”) from listview to the root element.
Run the app. You will get the output like below.
How does ListView know did user click on list item ??
Based on tapping sound.
No, Here comes Listener. Listener waits for the events. Such as tapping, touching events.
Here we use the OnItemClickListener nested class. Its onItemClick(…) method will trigger when an item in the listview clicked. So place the code that wants to run when click event happens.
Step 7
Create and Instantiate listview variable
In onCreate() method, create listview variable and instantiate using findViewById(int id) method. In this case, id is listview, we must use the same id in XML description. Type cast the returned View object to the ListView.
Add listener to listview for listening click events
Add OnItemClickListener and Implement OnItemClick(…) method. Use listview’s setOnItemClickListener() method to register the listener.
listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
}
});
Step 9
Display the content in the clicked item.
In onItemClick(…) method, Implement code to reveal the content in listview row. First, Use adapterview’s getItemAtPosition(int position) method to retrieve the data from listview item row. getItemAtPosition() returns data as object in the given position.