Home > Enterprise >  App crashing two linear layout inside other linear layout with java
App crashing two linear layout inside other linear layout with java

Time:02-16

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:

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);


}

}

CodePudding user response:

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);
  • Related