How does LayoutInflater work? - java

I am new to Android development, and I am curious about the phrase "Inflate a View", which is being thrown around in the Android development community.
I know it has to do with calling the Inflate method of the LayoutInflater class but I'm still yet to grasp the concept behind it. Does this basically mean returning a view by passing its ID just like JavaScript's document.getElementById() sort of thing or is there more to it? Any form of enlightenment will be appreciated.

It basically is the term used for instantiating an xml Layout file into an object to be used in the java code. You can do this by calling setContentView(R.layout.file name minus xml extension) or by using LayoutInflater. Only after inflating can you call its child Views. This is important to know because I have seen many questions on SO in which people have an app that crashes and it turns out that they are trying to reference a view like
EditText et = (EditText) findViewById(R.id.someID);
and they haven't called setContentView() to obtain the Layout which holds that EditText which results in a NPE since the EditText doesn't actually exist until the Layout is inflated.
I'm sure you have seen the docs on it but Here they are anyway

While the specifics are surely more complicated than what I'm going to say, I think the easiest way to think of inflating views is as the process of going from the xml layout file to the actual View objects. The inflation methods, which are peppered around a number of different classes, typically all take an id argument which you would set as R.layout.xxx.

Related

What does findViewById(android.R.id.content) do in Snackbar?

I have seen in Snackbars being passed this findViewById(android.R.id.content) argument. We can't pass getContext() method as it demands a View parameter. I have seen on internet that programmers pass this argument inside Snackbar, what does it really mean?
Also, since it asks a View argument can i pass like any view that i have in my xml file, for example, any imageview or any videoView. If i pass these as an arguments, would my code still work? If yes, isn't it a little unexplanatory in code about what's really going on?
what does it really mean?
It asks the hosting activity to find a widget whose ID is android.R.id.content. All activities have one of these, set up by the framework Activity implementation and its associated Window. It represents the main content area of the activity.
isn't it a little unexplanatory in code about what's really going on?
You are certainly welcome to add comments to your code to explain your choice.
The Snackbar documentation explains the role of the View:
Snackbar will try and find a parent view to hold Snackbar's view from the value given to view. Snackbar will walk up the view tree trying to find a suitable parent, which is defined as a CoordinatorLayout or the window decor's content view, whichever comes first.
Having a CoordinatorLayout in your view hierarchy allows Snackbar to enable certain features, such as swipe-to-dismiss and automatically moving of widgets.
With that in mind...
can i pass like any view that i have in my xml file, for example, any imageview or any videoView. If i pass these as an arguments, would my code still work?
Perhaps. It depends a bit on the UI of your app. If there is a particular CoordinatorLayout that you want to use with the Snackbar, pass it (or a child) to make(). Otherwise, any widget should work.

Attempt to invoke virtual method View.SetOnClickListener on a null object reference in Android [duplicate]

I know that we need to place setContentView() in the onCreate() method before initializing any view otherwise it will throw a null pointer exception.
But what is the reason for it?Is the setContentView() similar to the inflate() method?
before initializing any view
I do not know for certain what you mean by "initializing any view". Given the rest of your question, I am going to interpret this as meaning "call findViewById() on the activity".
You need to call setContentView() before calling findViewById(), because otherwise there are no widgets to find.
Is the setContentView() similar to the inflate() method?
setContentView() will use a LayoutInflater and inflate() under the covers, if you pass a layout resource ID into the setContentView() method.
If no content View is set then from where you will reference the views like EditText,TextView,ListVIew and all other components which you have used in your layout.
It is like you have items in your bucket and its cover is locked for safety, you came in house without bucket and forgot it in the car and your mom asked you to put items 1 by 1 on Kitchen counter , but you don't have bucket?? so first you will get bucket then you will take out items from it.
Simply first you have to have a Container in your activity so that you can reference its items by using their ID which are assigned in layout xml.
Hope it is clear to you.!
Ok. Agree with #CommonsWare. In some details, let say if you have some views defined in your xml layout file and you want to use those views in you activity, so in this case you have to call setContentView(<R.layout.xml_layout_name>) and after that to inititlalize view using findViewById(R.id.<view_name>) with resource name as your xml layout defined name.
Ok but why we have to call setContentView() ?
So when you call setContentView() application activity means android nutshell will render views and prepare view hierarchy for your activity from layout file. Just remember you have defined views in layout using xml file and you are using those views in Java code, so for that all works to preparing views for you will do setContentView() that's why when you call findViewById() without setContentView() then your application can not find views from view hierarchy and it will throw NullPointerException.
setContentView() similar to the inflate() method ?
Some how, because both are doing the same thing, rendering views from given xml layout files but scope of works is different. setContentView() provides views throughout your activity scope while inflate() will only gives you a view from the layout file, that's why whenever you have used inflate() you have to always use reference of return view to call findViewById() like
pseudo code only for your understanding,
View view = infalter.inflate(<R.layout.<file_name>>);
TextView mextView = view.findViewById(R.id.textView);
And yes, setContentView() uses the same inflater.inflate() method too.
And when setContentView() and inflate() not required?
If you are creating dynamically views, in java code then you don't have to required call either setContentView() or inflate().
Note: In old android version when you create a dynamically views using java code and you pass it to some ListView's header or footer it won't work. For this views must be inflated before set to the ListView.

Android: "Texting" List View?

I need some help.
I'm wanting to make an activity similar to this, but I'm not sure where to start.
Basically, it's like a texting UI, with the users question on the right and the answer on the left. I was going to use a list view for the sake of simplicity, but I dont' think it'd support this kind of structure.
I googled some layouts where I can scroll, but most of them require me to premake them, which isnt an option because its a dynamic chat log.
Does anyone here have experience with this kind of UI? Can you point me in any direction? I hate to ask such a strange question, but I don't even know how I'd word this situation on Google.
Thanks in advance.
What you're looking for is a ListView where you can return a different layout depending on whether the message is sent or received. A ListView is the most efficient implementation for this because its ideal for displaying a potentially large data set without having to keep a view in memory for every row.
This is achieved by extending the BaseAdapter in your application and overriding the getItemViewType(), getViewTypeCount(), and getView() methods (along with all the other methods required by a ListView adapter).
This is a good tutorial that serves as a walkthrough for this pattern.
Instead of using ListView, You may programmatically construct a viertical LinearLayout, and add TextView in each line, you can set the alignment of the TextView in lines accordingly.

How do ListActivities work with ListViews in Android?

As a C# developer I'm trying to get familiar with Java and more specifically, the Android framework.
I've created some very basic intro Activities, but I'm now trying trying to get a ListView up and running with 'databinding'. I found this sample code: http://developer.android.com/guide/topics/ui/layout/listview.html
I don't think I've fully grasped the concept of these views yet, because initially I figured that the ListActivity class that I created would be built as some sort of a user-control that I could simply replace my ListView with. When I look at the code though, it appears as though it's somehow trying to hook into an existing view which confuses me. (How do I call this ListActivity from my current activity, and how do I use it with my ListView?).
getListView().setEmptyView(progressBar);
Could someone please clarify what's going on? Perhaps I've become too .NET paradigm orientated and I'm not understanding the picture properly.
A ListActivity is an activity that assumes that you will set a layout with a list view in it with a certain id. It will then store that view in a variable so getListVew() will return it. Basically its a tiny bit of syntactic sugar to do what you can do yourself with 3 lines of code.
Really I don't think its worth using. You can use listviews in a regular activity, it takes 1-3 lines of code to do everything the ListActivity does, and you don't have problems if you name your listview with a different id or if you even decide to not have a listview down the road.

Why do i have to cast a Button?

This must be a really dumb question because I cant find an answer online.... I know that casting is changing one datatype to another. How is this button ever changing it's data dype? Button button = (Button)findViewById(R.Bla.Bla) Why cant we just write Button button = New Button() And then assign the xml to it another way? Please explain, I'm lost.
You can set a Button to a new button.
But findViewById returns a view. If you want to access any of its Buttonosity, you must cast, otherwise the reference isn't a button. There are times that may be okay, of course.
See In Android You can create the UI Elements in two ways:
1. create UI elements through layouts (.xml) files.
And to use them in java class map them to their corresponding class.
And to do so we have to call method findViewById(int id); which returns the view of that perticuler element with given id.and thus we have to type cast it to respective component.
And thus if you have created a element already in xml why will you create a different object again at java end. so just map the element created with xml file.
2. crate UI elements through java end.
To use this feature use have to create the elements in java with new keywords ex. Button button = new Button(); and then set the all properties on that object.
But But But,
According to android philosophy you should create UI in xml, and write your core business logic in java end. And with this concept you can write neet and clean application code.
But it is only recommended not compulsory at all. now its up to you....
and i think at starting you feel it different but after some time you will start loving it...
Thats the beauty of android.
Thanks. i hope, i answered your question throughly.
Also, remember that Button is a subclass of View. The findViewById() method returns a generic View (any View or subclass of View that you put in a layout file). The cast to Button is saying "It's okay - I know this is a Button, not just a regular View," which allows you to access properties and methods of the Button that aren't available in the View superclass.
final Button callButton = (Button) findViewById(R.id.callButton);
I believe that when finding an XML view using findViewbyId(), it returns the view in the UI, but the returned view must be cast in order to be used as a button within the Java code, and have access to the button methods.
There are ways to create a button in the Java code without specifying it in the XML, but this practice differentiates the UI from the logic.
Plus, declaring UI elements in the XML is better because it is makes the process changing entire layouts easy through usage of of setContentView().
You have two options to create View component in android including Button
1- Define it in a layout XML file and access it using (Button) findViewById(R.id.button)
2- Create it dynamically in the code e.g. Button button = new Button();
both has their own advantages and disadvantages, for example, defining the UI in layout xml makes your Activity concise and and give you more flexibility by separating the UI from the actual code
Dynamic UI creation is useful in many applications that needs to create Views on-the-fly

Categories

Resources