NOTE:

NOTE: Of late, I have been getting requests for very trivial problems that many of you are facing in your day-to-day work. This blog is not to solve your "project" problems - surely not a "Support" site.
I just love to share my knowledge in my spare time and would appreciate any questions or feedback on the articles and code I have shared. I also do appreciate thought-provoking questions that would lead me to write more articles and share.
But please do not put your day-to-day trivial problems here. Even if you do, you most probably would not get a response here.
Thanks

Search This Blog

x

Thursday 2 December 2010

Creating Android UI Programmatically


So far, in all my examples, I have been using the declarative way of creating an Android UI using XML. However, there could arise certain situations when you may have to create UI programmatically. Sincere advice would be to avoid such a design since android has a wonderful architecture where the UI and the program are well separated. However, for those few exceptional cases where we may need too… here is how we do it.
Every single view or viewgroup element has an equivalent java class in the SDK. The structure and naming of the classes and methods is very similar to the XML vocabulary that we are used to so far.
Let us start with a LinearLayout. How would we declare it in an XML?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</LinearLayout>
This just contains a TextView embedded in a LinearLayout. A very trivial example. But serves the purpose intended. Let me show how almost every single element here corresponds to a class or a method call in the class.  So the equivalent code in the onCreate(…)  method of an activity would be like this:
         super.onCreate(savedInstanceState);
      
        lLayout = new LinearLayout(this);
        lLayout.setOrientation(LinearLayout.VERTICAL);
        //-1(LayoutParams.MATCH_PARENT) is fill_parent or match_parent since API level 8
        //-2(LayoutParams.WRAP_CONTENT) is wrap_content
        lLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
        tView = new TextView(this);
        tView.setText("Hello, This is a view created programmatically! " +
                  "You CANNOT change me that easily :-)");
        tView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
        lLayout.addView(tView);
        setContentView(lLayout);

Like this any layout view can be created. But from this small example you can notice two outstanding things – very tedious to code for every attribute of the view. And any simple change in the view, you need to change the code, compile, deploy and only then you see the effect of the change – unlike in a layout editor. 


You can download the sample code here.

19 comments:

  1. Hello, isn't it better to use static constant from the class ?

    LayoutParams.FILL_PARENT instade of -1
    LayoutParams.WRAP_CONTENT instade of -2

    in the code.

    ReplyDelete
  2. Axel, Valid point. I have made the changes

    ReplyDelete
  3. Check this out for building Android UIs programmatically:
    http://code.google.com/p/table-layout/

    ReplyDelete
  4. check this out
    http://androidtutorials60.blogspot.com/

    ReplyDelete
  5. I'm starting to explore android development, i always prefer with other platforms to do everything with code. Is there any drawback on doing this on the android?

    ReplyDelete
  6. Thanx Mam ... Your blogs are always a sigh of relief ... Really helped my issue ..

    Regards
    Gaurav Chawla

    ReplyDelete
  7. hi,
    geetha mam,
    I'am murali ,i have some doubt about Custom listview, I want to put images in sdcard and i want store image paths in SQLite Database then i want show that images in listview ,Please tell me how it possible. My email id: muralivitt@gmail.com
    And Myblog: murali-androiddeveloper.blogspot.com

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Hi,

    I am looking for dynamic table layout which can render SQLite table...
    diff number of columns and width

    may I am greedy :-)
    -SenthilSB

    ReplyDelete
  10. very usefull, thanks

    ReplyDelete
  11. I tried to use thois code inside onClickListner so dat i cn change the layout dynamically during the prgm.. bt the application isnt even starting... :( Pls help mam.
    -Arjun Satheesh

    ReplyDelete
  12. Thank you very much geetha mam.... helped very much

    ReplyDelete
  13. hi mam,
    I'm building one android app in that i need to make imageview as invisible. so, please help me how to do so.

    ReplyDelete
  14. Hello Geeta Mam,
    Ur post are always informative,I have a question related to Listview.
    I am drawing listview programmtically even all the layout.
    The values in the listview are mobile contacts now i want to put checkbox in front of listview items(Contacts).I am facing problem in doing this.
    Please mail me ur suggestion.
    adi_it1988@yahoo.co.in

    ReplyDelete
  15. Hi Geetha madam,

    Am a android programmer.
    I want to display an image on top of another programtically.
    How can i do that?
    Please give me a suggestion.

    ReplyDelete
    Replies
    1. Please forward your suggestions to rajanikanth487@gmail.com

      Delete
    2. That depends on what you mean by "image on top of another". If you mean 'top' in the plane of the screen, then you can use two ImageView elements in either a LinearLayout or a RelativeLayout. If you mean in the Z plane (where X-Y is the screen), then the even simpler FrameLayout is ideal. Look up all these in the Google online docs. Finally, please remember what Sai Geetha said: 'this blog is not to solve your "project" problems - surely not a "Support" site.'

      Delete
  16. "Every single view or viewgroup element has an equivalent java class in the SDK." Even your example shows that is not quite true. There is no view or viewgroup element (nor any paret of them -- it turns out be a relation between elements instead) corresponding to the LinearLayout.add(View) method you use in your sample code. Simply saying that the element corresponds to the LinearLayout class does not address this.

    So a more comprehensive explanation of the correspondence would be highly desirable, especially if you can remind the reader where to find the correspondence described in Google's online docs. I can never remember where to find this, and it seems to me that they have documented it in a natural place to search only for some classes and not for others.

    ReplyDelete
  17. I like all your posts. Constructive feedback - Add a snapshot of the UI to make it more easier to understand

    ReplyDelete