Thursday 6 October 2011

Using RelativeLayout instead of the deprecated AbsoluteLayout



Yesterday, I had to rework the Android app I am currently working on to show a glassy overlay image in front of some background elements.

What I needed to achieve is something like the UI pictured above (if you have problems reading the Bulgarian labels on the screenshot, it is a cooking app and they read things like 'Salad', 'Soup', 'Chicken' etc.).

My first thought was to use the deprecated AbsoluteLayout to position precisely the glass mark where I wanted it. Still the 'deprecated' word sent shivers down my spine and I didn't go that way.

Then I briefly considered the FrameLayout, but as it turns out, RelativeLayout can do such job perfectly and elegantly.

Here's the relevant code:

RelativeLayout rl = (RelativeLayout)findViewById(R.id.outerRelative);
ImageView iv = new ImageView(this);
iv.setImageDrawable(getResources().getDrawable(R.drawable.glass_mark));
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.leftMargin = 53;
params.topMargin = metrics.heightPixels / 2;
rl.addView(iv, params);

The idea for the solution was courtesy of StackOverflow (you know SO rocks, don't you?) -- so thanks.