Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to add a view inside a view programmatically?

I want to do something like this:

View v1= new View(this);
v1.setBackgroundResource(R.drawable.pic1);

View v2 = new View(this);
v2.setBackgroundResource(R.drawable.pic2);

v1.addView(v2);

RelativeLayout.LayoutParams params;
rl = (RelativeLayout) findViewById(R.id.activity_main);
rl.addView(v1,params);

I know the code is wrong. It just show how I want to do.

Some websides said that viewGroup may help me to achieve this.

I had tried but never can v2 be shown on the screen.

Does someone can tell me how to achieve this?

like image 907
Ray Avatar asked Oct 14 '13 08:10

Ray


1 Answers

Views cannot contain other Views. It simply doesn't work this way in Android.

If you want to place a View inside a different View, the containing View must extend the ViewGroup class.

There are several classes that can help you achieve this:

  1. LinearLayout - if you want your views to be aligned vertically or horizontally.
  2. RelativeLayout - if you want your views to be positioned relative to each-other and/or the container
  3. There a many more.

Hope this helps.

like image 193
Gil Moshayof Avatar answered Sep 27 '22 19:09

Gil Moshayof