Best Practices: Layouts on Android (Programmatic VS Xml)

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.

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.

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 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..

Dynamic vs XML layout in Android?

Use layout XML resource files.

First, the resource sets (e.g., res/layout-land/ in addition to res/layout/) allow you to define multiple UIs to be used in different circumstances, with the system automatically choosing the right one as needed. The equivalent in Java would be one nasty set of if or switch statements.

Second, there are tools that can help you create those layout resources successfully. Even if the drag-and-drop GUI building of Eclipse isn't your cup of tea (e.g., you're using NetBeans), Lint will help point out flaws in your layouts, for which it will point out only a subset in the equivalent Java code.

Third, it tends to be more terse, so if you're typing this stuff by hand, the XML will be less typing.

Fourth, approximately 98% of all sample code you will find will use layout XML files, and approximately 98% of all UI answers you find here on StackOverflow (and other support resources) will assume that you use layout XML files. While you are free to avoid XML -- perhaps you were attacked by angle brackets as a young child or something -- you will be swimming upstream, fighting the current compared to what most Android developers do.

What is the best practice for creating layouts for all screen sizes and all screen densities in Android

I have some solutions for you

  1. Use ConstraintLayout
    (https://developer.android.com/training/constraint-layout/)
  2. Use PercentRelativeLayout (https://developer.android.com/reference/android/support/percent/PercentRelativeLayout)
  3. Sdp converter (https://github.com/intuit/sdp)

In my case. I use all of them. They can work together as well.

Which way of creating view is faster in android XML or drawing on Canvas

Good answer from Ollie C https://stackoverflow.com/a/9827887/603233:

The advantages of XML are:

 1. Ability to use layout editors (Eclipse)
2. Easier to preview layouts
3. Possible to benefit from auto-localisation of layouts
4. Easily maintain different parallel layouts for difference devices (screens)
5. Can get a sense of the layout by looking at it (easier than code)
6. Easy to break layouts down into pieces (fragments, includes, etc) to remove duplication
7. Keeps a separation between the visual design, and the functionality behind it

Android proper way to fit layout on all devices horizontally and vertically

Actually it depends on the scenario. Sometimes maintaining xml is efficient and easy sometimes dynamic calculation is necessary. You can go through the link https://developer.android.com/guide/practices/screens_support.html . It will give you some ideas. In your above code for width/height calculation sometimes you may not get proper result for some devices. Below is the code that will support all version of android device Resolution(Width, Height) accurately at runtime.

private void calculateDeviceResolution(Activity context) {
Display display = context.getWindowManager().getDefaultDisplay();

if (Build.VERSION.SDK_INT >= 17) {
//new pleasant way to get real metrics
DisplayMetrics realMetrics = new DisplayMetrics();
display.getRealMetrics(realMetrics);
realWidth = realMetrics.widthPixels;
realHeight = realMetrics.heightPixels;

} else if (Build.VERSION.SDK_INT >= 14) {
//reflection for this weird in-between time
try {
Method mGetRawH = Display.class.getMethod("getRawHeight");
Method mGetRawW = Display.class.getMethod("getRawWidth");
realWidth = (Integer) mGetRawW.invoke(display);
realHeight = (Integer) mGetRawH.invoke(display);
} catch (Exception e) {
//this may not be 100% accurate, but it's all we've got
realWidth = display.getWidth();
realHeight = display.getHeight();
Constants.errorLog("Display Info", "Couldn't use reflection to get the real display metrics.");
}

} else {
//This should be close, as lower API devices should not have window navigation bars
realWidth = display.getWidth();
realHeight = display.getHeight();
}
}

What is the advantage of using xml for layout?

What are the maintainability benefits of using XML for this?

  1. Separation of logic from presentation. This does help on larger projects when you need to refactor some code. If it is tightly coupled to the UI this job can become time consuming very easily if much of the presentation logic is in code.
  2. The structure of XML correlates nicely to the structure of a user interface, i.e., a tree like structure.

What are the performance benefits of using XML for this?

That all depends on the implementation I suppose. I doubt there are any appreciable performance differences, but I honestly don't know enough to say definitively what they may be.



Related Topics



Leave a reply



Submit