I have the following main.xml file with a LinearLayout
I faced a similar problem. In my case I wanted to add a LinearLayout at last position of another LinearLayout. To accomplish it, I did:
LinearLayout parentLayout = (LinearLayout) findViewById(R.id.parentLayout);
LinearLayout layout = new LinearLayout(this);
layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
// add others views to your linear layout
parentLayout.addView(layout, parentLayout.getChildCount());