1

I'm trying to programmatically pass the id of a layout.xml file to the View.inflate method but am not sure how I could go about that. I have a test bit of code that I'm tring to get working and, as you'll see I've tried passing this in as a String but that doesn't work.

Any ideas? My thanks.

LinearLayout main = (LinearLayout) findViewById(R.id.mainLayout);    
for (int i = 0; i < 3; i++) {
        String boxToInflate="R.layout.box"+Integer.toString(i);
        LinearLayout ll = (LinearLayout) View.inflate(MainActivity.this, boxToInflate, null);
        main.addView(ll);
}

Edit: A few minutes later.

I think I may be making some progress with this test code:

    // Get outer relative layout
    LinearLayout main = (LinearLayout) findViewById(R.id.mainLayout);
    for (int i = 0; i < 3; i++) {
        // String boxToInflate="R.layout.box"+Integer.toString(i);
        int resID = getResources().getIdentifier("box" + i, "id",
                getPackageName());
        LinearLayout ll = (LinearLayout) View.inflate(MainActivity.this,
                resID, null);
        main.addView(ll);
    }
Roger W
  • 107
  • 1
  • 4
  • 16

1 Answers1

2
int layoutId = getResources().getIdentifier("box"+i, "layout", getPackageName());

It also works for other things like drawables ("drawable" instead of "layout"), etc. Just replace the second parameter.

EDIT : Saw your edit, just replace "id" with "layout" and you're good.

Stephane Mathis
  • 6,542
  • 6
  • 43
  • 69