0

I am trying to programmatically add LinearLayouts inside an existing RelativeLayout. Each LinearLayout will contain some buttons and I want to be able to toggle the visibility of each set of buttons by setting the visibility of the container LinearLayout.

// We iterate over a list and call the following to create the new
// layout assigning an index from a int counter
LinearLayout LL = new LinearLayout(MainActivity.this);
LL.setOrientation(LinearLayout.VERTICAL);
LL.setId(nextId);

LinearLayout.LayoutParams LLParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);

LL.setWeightSum(6f);
LL.setLayoutParams(LLParams);

LinearLayout mll=((LinearLayout) findViewById(R.id.menuLayout));
mll.addView(LL);

My problem comes when I try to retrieve these layouts later, for instance to be able to toggle their visibility on/off. I thought I would be able to use

LinearLayout ll = (LinearLayout) findViewById(layoutIndex);

But findViewById() gives me an error when I try to supply an int, it wants a resource ID. Is there an easy way I can convert the ints that I have assigned as the Ids for these layouts to R.id.XXX ids?

Thanks, Andy

Darek Kay
  • 15,827
  • 7
  • 64
  • 61
user2255700
  • 93
  • 2
  • 8
  • 2
    Possible duplicate of [How to set Id of dynamic created layout?](http://stackoverflow.com/questions/8937380/how-to-set-id-of-dynamic-created-layout) – dabo248 Nov 10 '15 at 23:19

2 Answers2

1

findViewById(id) looks up elements that were included as part of the XML defining a layout.

You will probably have better luck with getChildAt(index), which returns the View at the passed index.

emerssso
  • 2,376
  • 18
  • 24
0

Yes! Find all LinearLayout in a container without using ID.

LinearLayout mll= (LinearLayout) findViewById(R.id.menuLayout);//container

 for(int i=0; i<mll.getChildCount(); ++i) {
     View nextChild = mll.getChildAt(i);
     if (nextChild instanceof LinearLayout ) {
         //TODO add your code here nextChild is a LL that you wanna find
     }
 }
T D Nguyen
  • 7,054
  • 4
  • 51
  • 71