Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

App crashing two linear layout inside other linear layout with java

Hey Everyone I want to make a layout in android studio dynamically(not with xml) the structure will be like :
LinearLayout(Horizontal)
–LinearLayout(Vertical)
—-TextView1
—-TextView2
–LinearLayout(Vertical)
—-TextView3
—-TextView4

but the app is crashing with error:
The specified child already has a parent. You must call removeView() on the child’s parent first

Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class MainActivity extends AppCompatActivity {

LinearLayout linearLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

   LinearLayout HLL = new LinearLayout(this);
   LinearLayout V1LL = new LinearLayout(this);
   LinearLayout V2LL = new LinearLayout(this);

   HLL.setOrientation(LinearLayout.HORIZONTAL);
   V1LL.setOrientation(LinearLayout.VERTICAL);
   V2LL.setOrientation(LinearLayout.VERTICAL);

   V1LL.setBackgroundColor(Color.parseColor("#fcba03"));
   V2LL.setBackgroundColor(Color.parseColor("#fc03e3"));

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

    LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(
            0,
            LinearLayout.LayoutParams.MATCH_PARENT,
            1
    );


   setContentView(HLL,lp);
   setContentView(V1LL,lp);
   setContentView(V2LL,lp);

   HLL.addView(V1LL);
   HLL.addView(V2LL);


}

}

>Solution :

why are you setting setContentView multiple times? Activity can contain just one View as content (but this may be ViewGroup with multiple childs). just add inner LinearLayouts to main parent LinearLayout and then call setContentView passing only this main one

HLL.addView(V1LL);
HLL.addView(V2LL);

setContentView(HLL, lp);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading