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

Friday, 3 December 2010

Android UI – Inflate from XML (Dynamic UI Creation)


We have seen that we can declare User Interface in Android through XML or we can even create the UI Programmatically. Now, we will see how we can mix the two and use it for building dynamic User Interfaces. One example of such a case would be when on a particular action of the user on one of the UI elements, you need more UI elements to appear on the same screen. How do we achieve this?
You can do it in two ways:
1.       The dynamic part of the UI can be created programmatically. However we saw in my earlier tutorial that it is not a very good way to mix UI and code.  So, we can
2.       Define the dynamic UI too as an XML and use XML inflation to include it into the existing UI.
We will see how to do the 2nd way, which probably is a good practice too.
As always, again a very simple example. Assume I have a very simple linear layout. In that I want to include a button. I can do it as part of the mail XML itself. However, assume that this button is supposed to be reused in many activities and hence I have defined it as a separate XML. How do I include it into the main XML?
So, here is the main.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"
    android:id="@+id/layout1"
    >
</LinearLayout>
Here is the buttons.xml that is also created in the res/layout folder:
<?xml version="1.0" encoding="utf-8"?>

<Button xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/button_small_left"
 style="?android:attr/buttonStyleSmall"
        android:text="Press to close"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
And here is the Activity’s onCreate(…) method of the InflateView class:
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final LayoutInflater  inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Button b = (Button)inflater.inflate(R.layout.buttons,
                null);
       
        lLayout = (LinearLayout)findViewById(R.id.layout1);
        lLayout.addView(b);
First 3 lines must be familiar. In the 4th line, I am getting a handle to the LayoutInflater through the getSystemService(…) method.  This inflater has a method inflate to which I pass the buttons.xml by passing the parameter R.layout.buttons. Then, I try to append this button to the Linear Layout that already exists and is set as the view in line 2 setContentView(R.layout.main). How to append? I get a handle to the LinearLayout lLayout and add the new button to it in the last line!
That simple to inflate an XML and append it to an existing view!
However, I have gone ahead and added another bit to this program as shown below:
        b.setOnClickListener(new OnClickListener() {
           
            public void onClick(View v) {
                  //restrict to adding only 1 textview child element
                  if (lLayout.getChildAt(2) == null)
                  {
                  TextView tv = (TextView)inflater.inflate(R.layout.text, null);
                  lLayout.addView(tv);
                  }
            }
        });
On the click of this dynamically added button, I am showing how we can add more to the UI dynamically through inflation. Assume, on the click of the button, you want to show some new text. This TextView is defined in another XML called text.xml which is also in the res/layout folder.
So, I am inflating from this XML and appending it to the LinearLayout view. So, a lot can be achieved for dynamic UI through inflation.

You can download the complete sample code here.

34 comments:

  1. Hi Sai Geetha,

    is it possible to display AlertDialog box in home screen, when send sms.i want display AlertDialog box at receiver side.

    ReplyDelete
  2. Hi, Thanks. It is very useful.

    ReplyDelete
  3. How do I draw on a View element defined in main.xml, like the one below;

    ReplyDelete
  4. Hello Sai,

    I have a question about Android development and was surfing the web when I found your blog. I know this isn't related to the topic of your post (sorry), but is there a way to modify the phone icon behavior on the Motorola Droid? I've been asking this question for a week or two in general forums and I decided maybe I should look at writing my own solution, so I started looking for tutorials and found this blog.

    My problem is this: my wife and I both have the Moto Droid and my wife has downloaded several pre-school apps (Sesame Street videos) for our 2 year old. He know how to find and start the videos, but the problem is that he will also press the phone icon on the home screen which brings up the call log. Then he hits the phone icon and calls that person... an annoying thing! Is there a way to modify the Droid code so that when the phone icon is pressed, a password field and the android keyboard come up. She would then type in a short password before the process called up the call log screen.

    Anyway, that's what I'm looking for... do you have any ideas?

    Thanks,
    gpence61

    ReplyDelete
  5. Hi to the AlertDialog Questioner!

    Why would you want to show an AlertDialog on the homescreen to an end user. It would be very intrusive and user experience. Notification bar exists exactly for that reason to non-intrusively show the arrival of an SMS. And this is already implemented in the default behaviour of the phone.

    ReplyDelete
  6. Hi Rend,
    You have missed out sharing what you intended to share below your comment

    ReplyDelete
  7. Hi gpence61,

    Getting a password screen on touching the phone icon will have to be a custom solution developed as by default no one would want such a feature - meaning more touchs before you can make a call!

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

    ReplyDelete
  9. In case gpence61 is still following this and hasn't found a solution yet: The app from the Market called "tasker" can be used to achieve what you want. You would maybe have to create your own action inside the app, but it is definitely capable of doing it.

    I have stumbled across this blog looking for a nice solution to create different ui-elements generically, as part of a customizable settings screen. Even though this guide lets you reuse and dynamically add your button, how would you go ahead and add a series of buttons with different text to your gui? Good read anyways!

    ReplyDelete
  10. Hi Geetha,

    Is it possible, I need to display textView underneath the default incoming call screen. Not as a toast but it should be there till call lasts.

    I saw you have done some marvelous jobs in android if you find a way would you please suggest me.


    Thanks,
    Ketan

    ReplyDelete
  11. Very useful tutorial.

    Thanks.

    ReplyDelete
  12. Hi Geetha,
    Is there any way to programatically disable the phone radio (any equivalent of setradio as it is deprecated).

    ReplyDelete
  13. Pardon my ignorance, But why is this check being made if (lLayout.getChildAt(2) == null)??

    I see the comment above it. But I don't quite understand (//restrict to adding only 1 textview child element)

    ReplyDelete
  14. Hi Geetha,
    Currently I'm stuck with the list UI with 2 textview and 1 radio button. The list will be pulled out of from DB. Do you have any good example that I can refer? My email : george.nguyen79@gmail.com
    Thanks
    - George

    ReplyDelete
  15. hi sai geetha, i need screen lock code in android. please help me

    ReplyDelete
  16. I am trying to lock the screen on click a button.

    ReplyDelete
  17. Hi Sai,

    It is mentioned in the android documentation that when before you override the activity call back methods the super methods of activity class should be called. THe same is not applicable in the case of service. What could be the reason?

    ReplyDelete
  18. great stuff, i was doing (well trying to follow number 1) but this seems much cleaner and efficient.

    ReplyDelete
  19. Hi Sai,

    I would like to know if i want to repeat adding the same UI again, should i inflate again and then add or any work around, Also any effect on memory if i repeat the above step say 10 to 15times.

    ReplyDelete
  20. Hey, many thanks, it helped my designing my GUI.

    ReplyDelete
  21. i want how to create multiple buttons on screen for example calculate program please give me any information.

    ReplyDelete
  22. hi mam, nice tutorial..it helped a lot...

    ReplyDelete
  23. Hi am implementing the android application for to access the project management application that has different workitem like task and stories. But these work items can be customized as per the project needs and the structure is saved as a XML file in the server. Now my android application wants to display those work items based on its structure in the server. How can I implement this so that wi structure in my android apps is in sync with the structure in the server. Thanks in Advance.

    ReplyDelete
  24. Hi Sai,

    Your tutorials are so so simple and easy to understand. Thank you very much for all the effort and sharing your knowledge with us.

    Debayan

    ReplyDelete
  25. Hi saigeetha,

    is it possible to have the XML file outside of the APK file, and the changes we made in the XML file will dynamically reflect on the UI at run time.?

    thanks

    ReplyDelete
  26. Hello from Brazil!
    Thanks, you saved me ^^
    ;*

    ReplyDelete
  27. hi
    please help...i m designing a ui in android using visual studio
    i am not able to scale the widgets dat i use...they tend to overlap
    wat should i do

    ReplyDelete
  28. Thanks for the blog and making things simple Geetha.

    Vinay

    ReplyDelete
  29. Hey, thanks for this great tutorial. This is the only one I've found which actually gives you a complete code, not just the 2 lines when inflating.

    I've successfully adapted this code to fit my needs, and I created a method that will inflate a RelativeView into a layout. If I call that method once, it adds the RelativeView, however if I call it the second time, nothing happens. I've seen in your code that you're only handling inflating once, but is it possible to insert a View multiple times beneath each other?

    My first guess was that the 2 Views got inserted but they were on top of each other, but I changed the "top" property of each, and there really was only 1 View.

    Any help on this would be great. Thank you again for this tutorial!

    ReplyDelete
  30. Really Good!.. Thanks a lot!.. :)

    ReplyDelete
  31. Thank you for this tutorial

    ReplyDelete
  32. Hi Please could you explain me about getView method in custom adapter with its parameter in detail. thanks

    ReplyDelete