0

Most Layout files created in xml can be created through code. For example, below snippets in xml & java serve the same purpose :

<LinearLayout
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:orientation="horizontal">
               <ImageView
                   android:layout_width="match_parent"
                   android:layout_height="match_parent"
                   android:background="@drawable/allstar1"
                   android:layout_weight="1"/> 
                   ..
                   ..
</LinearLayout>

Java :

        LinearLayout l_row = new LinearLayout(this);
        l_row.setOrientation(LinearLayout.HORIZONTAL);
        LinearLayout.LayoutParams lParam1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT,1f);
        lParam1.weight = 1.0f;
        lParam1.gravity = Gravity.CENTER;
        l_row.setLayoutParams(lParam1);
        LinearLayout.LayoutParams r_Param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            r_Param.weight = 1.0f;
            r_Param.gravity = Gravity.CENTER;

        for(int j=0;j<cols;j++)
        {
            ImageView iv = new ImageView(this); 
            l_row.addView(iv); 
            iv.setLayoutParams(r_Param); 
        }

I generally prefer (going with the flow and) creating my layouts & other controls in the code. I have been thinking about the possible disadvantages. I didn't find anything on the internet.

I want to know the difference between these two approaches in terms of :

  • Impact on memory consumed
  • Impact on speed
  • Code re-usability/size
  • Maintainance
  • Anything else that I should be knowing

Is there any significant advantage/disadvantage? Or using a particular approach is solely a matter of personal choice ?

Thanks & Regards,

SwaS

Swas_99
  • 2,350
  • 1
  • 15
  • 19

1 Answers1

0

XML: Mainly static pages. You expect certain number of objects to display.

JAVA: Dynamic rendenring. For example, you may call a web service to give you a list of items for a table, but you don't know how many items you will get back. So therefere you can render your page programmatically to fill a table with x items vs. A set number of items.

You can also calculate the screen size of the device your using, that way you can set the LayoutParams width and height dynamically.

Both of them have their advantages bit keep it simple. Memory wise and processing time xml should have the up hand because memory is already allocated and there are less things to process. With Java or programmatically your application will do more work because you have to specify a lot more code.

Xml and java are both reusable depending on how you structure out your project. That really comes down to code design not xml vs java.

TerNovi
  • 390
  • 5
  • 16