Android xml vs java layouts performance
A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. You can declare a layout in two ways:
Declare UI elements in XML. Android provides a straightforward XML
vocabulary that corresponds to the View classes and subclasses, such
as those for widgets and layouts.Instantiate layout elements at runtime. Your application can create
View and ViewGroup objects (and manipulate their properties)
programmatically.
The Android framework gives you the flexibility to use either or both of these methods for declaring and managing your application's UI. For example, you could declare your application's default layouts in XML, including the screen elements that will appear in them and their properties. You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time.
The ADT Plugin for Eclipse offers a layout preview of your XML — with the XML file opened, select the Layout tab.
You should also try the Hierarchy Viewer tool, for debugging layouts — it reveals layout property values, draws wireframes with padding/margin indicators, and full rendered views while you debug on the emulator or device.
The layoutopt tool lets you quickly analyze your layouts and hierarchies for inefficiencies or other problems.
The advantage to declaring your UI in XML is that it enables you to better separate the presentation of your application from the code
that controls its behavior. Your UI descriptions are external to your
application code, which means that you can modify or adapt it without
having to modify your source code and recompile. For example, you can
create XML layouts for different screen orientations, different device
screen sizes, and different languages. Additionally, declaring the
layout in XML makes it easier to visualize the structure of your UI,
so it's easier to debug problems.
When you compile your application, each XML layout file is compiled into a View resource. You should load the layout resource from your application code, in your Activity.onCreate()
callback implementation. Do so by calling setContentView()
, passing it the reference to your layout resource in the form of:
I think its too much just visit this link http://developer.android.com/guide/topics/ui/declaring-layout.html and get more information..
Could there be any performance difference between writing the same code (for the layout) in XML or java file?
creating the ui hierarchy by hand in your activity class will be faster but MUCH more complicated than using xml layout files (about the LayoutInflater performance see its createView(String name, String prefix, AttributeSet attrs)
method used when inflating the layouts and you will find out its not a speed daemon), i cannot give you any numbers in % though
Android - Layouts performance: Programmatic vs XML
For most practical intents and purposes, there is no significant performance impact to either approach. It might be relevant if you needed to inflate an incredibly large number of a particular layout, at which point you might try benchmarking it yourself to see if there's any real difference, but otherwise I'd be hard-pressed to envision a scenario that results in a significant impact either way.
Suppose you have a layout:
<LinearLayout xmlns:android="..."
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
... >
<Button
android:id="@+id/some_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/my_button_bg"
android:text="Hello World" />
<!-- other views ... -->
</LinearLayout>
What happens is Android compiles this file into a binary format and packages it in the APK. When you use LayoutInflater
at runtime, it will load a block of this binary format into memory and parse it, and build the view hierarchy from the contents, very similar to what you would do by hand in code. That parsing is all done in native code, so it's likely much more optimized than your typical XML parsing in java.
LayoutInflater
constructs the views using reflection when it encounters a tag (e.g. <Button .../>
). The first time it must look up the constructor for that particular view; thereafter it will cache the constructor for faster access later.
Where you would normally call mutators like button.setText(...)
, button.setBackground(...)
, etc., typically the views call these methods on themselves during inflation. That is, the code path being traversed through the view's constructor will perform those mutations based on the attributes parsed from the binary XML format. This is because LayoutInflater
uses the two-argument constructor which accepts an AttributeSet
. The implication here is that when you build views by hand, some of these methods may end up getting called twice.
For example, take the Button in the sample layout above. Buttons already have a default background (how this is actually provided is itself interesting, but not very important here), so even calling the one-argument constructor with just a Context
still gets you a Button
with the default background. In other words, the code path includes a call to setBackground(...)
(or some equivalent) with the default background image. Then later you have to call setBackground(...)
yourself with the custom drawable resource named in the XML file. It's difficult to say off hand what impact this has because it really depends on the implementation of individual views and what mutations you are making.
One final thought: I have built an app in a professional environment that avoided all use of XML (as much as possible, including things other than layouts). I can tell you without hesitation that it is immensely annoying and increases development time dramatically. I'm very good at it and it still takes far longer than doing it in XML. Additionally:
- The code tends to be extremely verbose
- You don't get the benefit of all the tooling built around XML layouts in the IDE
- Even without the tooling, just the XML file alone gives you a clear representation of the view hierarchy
- You may have to know about certain idiosyncrasies of the UI framework (some of which may depend on API level)
- It's not always possible to map an XML attribute to a corresponding mutator method in java (again sometimes depending on API level)
- Calculating dimensions gets a lot more interesting
- Remembering which LayoutParams to use where is great mental gymnastics
There are probably other reasons, but those are just off the top of my head. Don't get me wrong, there are plenty of times where manual manipulation of views and hierarchies is valuable, but I wouldn't substitute inflation for that.
What is better to use for creating layouts. Java or XML?
Most of the time I prefer layout XML resource
files, but it varies according to the need.
First, the resource sets (e.g.,
res/layout-land/
in addition tores/layout/
) allow you to define multiple UIs to be used in different circumstances.layout-land -> for landscape
layout-port -> for portrait
layout-v15 -> for android version >= 15
layout-sw600dp -> for screens with a certain width
Second, there are tools that can help you create those layout resources successfully. drag-and-drop GUI building of Eclipse is one of them.
Third, it tends to be more terse, so if you're typing this stuff by hand, the XML will be less typing.
In Java code you have to compile & run the code to see how the layout looks like, while in XML (if you are using eclipse) you can see it directly with the tools that eclipse provides.
For everything static I use XML, because it is easy to find in the structure of your project.
But in some cases, you want to create dynamic layouts and you have no other choice then to use Java Code. Be smart, in this, so if you have to add several Views that look the same do this
From my perspective,
xml layouts
are good if you want android to
handle the layouts automatically. This would be for things like
data-entry type applications (like banking applications). Java layouts
would be better for applications that need tight control of the UI
(like angry birds)
Best practices: Layouts on Android (Programmatic vs XML)
I use XML layouts on pretty much every fragment and activity of every app I write. I very rarely see any need to create Views dynamically, tho configuration of ListViews, showing/hiding views, etc needs doing in code. For me the advantages of XML are:
- Ability to use layout editors (Eclipse)
- Easier to preview layouts
- Possible to benefit from auto-localisation of layouts
- Easily maintain different parallel layouts for difference devices (screens)
- Can get a sense of the layout by looking at it (easier than code)
- Easy to break layouts down into pieces (fragments, includes, etc) to remove duplication
- Keeps a separation between the visual design, and the functionality behind it
I can't think of any good reasons to put all my layouts into code - that sounds like hell.
I expect the reason your layouts don't look the same is because your XML is not defining the layouts correctly. Bear in mind the Android tools convert XML layouts into code, so there's no inherent problem with using XML layouts versus dynamic - both end up as code.
Should I use Java or XML for Android layouts?
An advantage of XML layouts are better is that they permit to define multiple layouts with smaller code
for multi-language application u can define French and english UI and load the desired one at application startup
they permit to support many screen resolutions and orientation (define main.xml file for each profile)
also u can easily add and modify layout without touching u'r code
so, better to USE IT
Performance: Android views generated programmatically vs xml views
The performance is not affected, but each has its pros and cons. Just to name a few:
XML
Pros
- The UI separated from code
- You can reuse layouts, combine them
- Faster development, you can check the UI in preview, without rebuilding the app
Cons
- Its static
Programatically
Pros
- React to runtime conditions
Cons
- more code (e.g. harder to maintain your code, more potential bugs)
Related Topics
Display Data After Every 10 Seconds in Android
Require a Password to Uninstall/Remove Application
Setting System Time of Rooted Phone
Android - Add Textview to Layout When Button Is Pressed
Equivalent of Clean & Build in Android Studio
Com.Google.Android.Gsf Package Couldn't Be Found
Android Set Button Background Programmatically
Httpentity Is Deprecated on Android Now, What's the Alternative
Generating Google Map Release API Key
Enable and Disable Auto Rotate Programmatically
Modifying the Android Seekbar Widget to Operate Vertically
Programmatic Screencapture on Mobile Device
Android Studio How to Run Gradle Sync Manually
Need to Disable Expand on Collapsingtoolbarlayout for Certain Fragments
How to Programmatically Launch a Specific Application
Exif Orientation Tag Value Always 0 for Image Taken with Portrait Camera App Android