[Tuto] Create an Android UI programmatically


Sometimes we need to create an interface programmatically to computerize some processing like create a form dynamically. It’s the subject of this post. You can found above an example.

Let’s Go !


We begin with a simple XML file that contain a RelativeLayout and we add programmatically a button at the center.

We will finish with a result that equal to this :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    <Button android:id="myButton" android:layout_width="wrap_content"
        android:layout_centerInParent="true" />

How ?

Like that :

public class MaClasseIHM{
    private RelativeLayout myRelativeLayout;

    public void onCreate(Bundle savedInstanceState) {
        myRelativeLayout = (RelativeLayout)findViewById(R.id.myRelativeLayout);

        // We create a button
        Button myButton = new Button(this);

        // The LayoutParams class permit to setting our element (the button)
        // Here the height and length
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        // Here we center myButton
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);

        // And to finish, we add the button at our RelativeLayout with layoutParams
        myRelativeLayout.addView(myButton, layoutParams);

You have now all elements to create a more complex UI.

To go further

You know now how to create a button. It’s not very usefull but it can become usefull if you need to create a lot (one hundred for example) through the loops ! :)

If you need to create a more complex interface like a form, you can create a class that extends RelativeLayout. After it, you can create easyly a lot a of this new element by instanciate it.

If you have any problem, don’t forget the android documentation or comment this post :)

Leave a Comment

* Copy this password:

* Type or paste password here:

1,548 Spam Comments Blocked so far by Spam Free Wordpress

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>