2

I'm trying to add a View on top of another one.

First I am setting a view via the xml and then I want to add the second one programatically. public void onCreate(Bundle savedInstanceState)

{
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  LinearLayout ll = (LinearLayout) findViewById(R.id.layout);
  drawView = new DrawView(this);
  drawView.setBackgroundColor(Color.TRANSPARENT);
  Bitmap bitmap = Bitmap.createBitmap(10, 100, Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(bitmap);
  drawView.draw(canvas);
  drawView.setLayoutParams(new LayoutParams(800, 0, 0.18f));
  LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)drawView.getLayoutParams();
  params.setMargins(0, 0, 0, -130);
  drawView.setLayoutParams(params);
  ll.addView(drawView, 2);

}

My problem is that the xml is on top of the view that I am trying to add.

How can I make the second view on top?

Dhasneem
  • 4,037
  • 4
  • 33
  • 47
roiberg
  • 13,629
  • 12
  • 60
  • 91

3 Answers3

2

LinearLayout is a layout that arranges its children one after the other vertical or horizontal. If you want to stack views one on top of the other then use a layout that allows that, like a RelativeLayout, instead of the LinearLayout.

user
  • 86,916
  • 18
  • 197
  • 190
  • shouldnt margin do the trick too? or thats what hapens whan you use margin in a linear layout? – roiberg Apr 19 '12 at 08:02
  • @roiberg I don't know your exact layout to see what is happening but I don't think the margins will work. And even if it works you'll probably don't want to do use margins if you want to make your app look decent on all phone screens and not just the current one. – user Apr 19 '12 at 08:19
2

If you want to stack views one over another you should use Relative Layout. So in your case replace "layout" with Relative layout, in java code you can do something like below.

    RelativeLayout.LayoutParams baseLayoutParam = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    baseLayout.setLayoutParams(baseLayoutParam);
    DrawView drawView = new DrawView(context);
    RelativeLayout.LayoutParams rLayoutParams = new RelativeLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, (int) (250 * Utility.getDip(context)));
    rLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT); // Adjust accordingly to your requirement
    drawView.setLayoutParams(rLayoutParams);ll.addView(drawView);
NyanLH
  • 480
  • 1
  • 6
  • 17
0

You can call the view's bringToFront method:

drawView.bringToFront();
Tony the Pony
  • 40,327
  • 71
  • 187
  • 281