2/13/2011

Programmatically creating a Layout Part 1: LinerLayout vertical order

I guess there are a few tutorials on how to create Android layouts using only Java so I'm not really telling you anything totally new but I don't really care. You'll certainly not find any tutorial on this subject featuring an unicorn.

Me and my unicorn friend Fred will try to throw some light on the subject of creating layouts via code in a couple of somewhat shorter parts each dealing with another aspect of the layout creation process.

So lets start. First of all why would you create your layouts via code instead of just using the way more comfortable XML files? Well there is more than one answer to this question.

Some like XML others don't. It is a personal preference. There is absolutely nothing you can't do with Java compared to XML in terms of layouts.

Another point is that creating layouts via code might be more performant as Android does not have parse and create the layout for you as that is what happens in the background when using a layout defined in XML but I think that this is a marginal thing.

Now lets start off with the LinearLayout (yes that is a link to the reference page, use it!).

A short explanation of the concept. If you want to hold more than one object you will need a ViewGroup. That is some kind of container which will hold your views. This ViewGroup which in our case is a LinearLayout needs some layout parameters to know how it should scale inside of the window. After creating the container and defining its layout parameters you create a View like a TextView for example. Set some text and maybe another background color for that view. Define its layout parameters the way you did on the LinearLayout. On a View you have to set the layout parameters by calling the setLayoutParams() method. If all is set for that View add it to the container it should be displayed in using the addView() method on the LinearLayout. You have to pass that method the View you want to add and you may also add the layout parameters as a second parameter (we will cover both methods). Finally you set the LinearLayout containing all of your views as the content view of your Activity by setting it as a parameter on the setContentView() method, the second parameter is the optional LayoutParams object you have defined earlier.

So now that you know the rough concept we'll dive into some code. First we are going to look at a LinearLayout with a TextView, an ImageView and a Button in a vertical order.
public class CodeLinearLayoutVertical extends Activity {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Grabbing the Application context
        final Context context = getApplication();
        
        // Creating a new LinearLayout
        LinearLayout linearLayout = new LinearLayout(this);
        
        // Setting the orientation to vertical
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        
        // Defining the LinearLayout layout parameters to fill the parent.
        LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.FILL_PARENT);
        
        // Creating a new TextView
        final TextView tv = new TextView(this);
        tv.setBackgroundColor(0xFFFF00FF);
        tv.setTextColor(0xFF000000);
        tv.setTypeface(null, Typeface.BOLD);
        tv.setText("Where is Fred?");
        tv.setGravity(Gravity.CENTER_HORIZONTAL);
        
        // Defining the layout parameters of the TextView
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
        
        // Setting the parameters on the TextView
        tv.setLayoutParams(lp);
        
        // Adding the TextView to the LinearLayout as a child
        linearLayout.addView(tv);
        
        // Creating Fred
        final ImageView iv = new ImageView(this);
        iv.setImageResource(R.drawable.fred);
        iv.setVisibility(View.GONE);
        
        // Defining the layout parameters of Fred
        lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
        
        linearLayout.addView(iv, lp);
        
        // Creating a new Button
        Button btn = new Button(this);
        btn.setText("Call Fred!");
        
        // Setting the Buttons OnClickListener
        btn.setOnClickListener(new View.OnClickListener() {
   
            @Override
            public void onClick(View v) {
    
                if (!iv.isShown()) {
                    Toast.makeText(context, "Hello Fred", 
                        Toast.LENGTH_LONG).show();
                    iv.setVisibility(View.VISIBLE);
                    tv.setText("There is Fred!");
                } else {
                    Toast.makeText(context, "I'm already here!", 
                        Toast.LENGTH_LONG).show();
                }
            }
        });
        
        // Defining the layout parameters of the Button
        lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
        
        // Setting the parameters on the Button
        btn.setLayoutParams(lp);
        
        // Adding the Button to the LinearLayout as a child
        linearLayout.addView(btn);
        
        // Setting the LinearLayout as our content view
        setContentView(linearLayout, llp);
    }
}

As you can see most of it is already commented. So I'm not going to repeat all the above. What might be a bit confusing is why we need that Context on line 8. We need it for the Toast messages in the OnClickListener starting on line 57.

On line 23 and 24 I set colors. As you can see the color value is quite interesting. It is a hex value coded like this: 0xAARRGGBB the 0x highlights that it is a hex value. The A stands for the alpha channel, the R for the red channel, the G for the green channel and the B for the blue channel.

With setTypeface(null, Typeface.BOLD) on line 25 I'm making the text bold. Line 27 does nothing else than the android:gravity="center" would do; it sets the text gravity to center.

Line 35 sets the layout parameters for the TextView and line 38 adds our TextView to the LinearLayout. Another interesting line is line 44. Here we are setting the ImageViews visibility to gone which does two things. It will not be visible and it will not take up the space the view would normally take up. I guess you are asking yourself why it is not visible. Well unicorns are very shy creatures.

Line 50 is noteworthy. Remember when we set the layout parameters on the TextView and then added it to the LinearLayout? It is basically the same thing but in one step.

I've mentioned line 57 earlier when I told you why we need a Context object. Now here is what happens inside of this OnClickListener (which is an anonymous inner class in this example. You should be able to name the different elements of a class). First we check if the ImageView is not visible by calling isShown() on it. If it is not visible we first display a Toast message, then set the visibility of the ImageView to visible and change the text of the TextView. If it is visible and the Button is clicked again we display another Toast message.

Last but not least on line 86 we set the LinearLayout as our content view.

Here is how it initially looks like.

Initial state
 When you click the Call Fred! button it will look like this.

Fred appeared!

And this is how it looks like when clicking again.

You're pissing Fred off!

Thats pretty much it. If you want to have such a beautiful unicorn too then visit blapha's site Unicornify!

3 comments:

  1. thanks a bunch!
    There are a lot of people that talk about it but dont give fully functioning code examples for new devs like me. your article just made my work a LOT easier.

    THANKS

    ReplyDelete
  2. Thanks.................
    Sir I am beginner android developer and Blog writer.
    How can I post the Code in the Format you used... I post code but i display like simple text. how can I do it...plz help me..

    ReplyDelete