Search code examples
androidxmllayoutsetcontentview

Load a layout from XML and add views


I'm trying to load an existing layout from XML and then create dynamically a button and a Circle, the reason which I cannot include them onto the XML is because the purpose is to create Circles dynamically, actually the following code is a snippet of what I want to create.

I know the way I am doing this (adding the layout) is wrong, but after reading a lot of Internet content I failed to did it by myself, because that I request help.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_etest);
    LayoutInflater inflater;
    inflater = this.getSystemService
    (Context.LAYOUT_INFLATER_SERVICE);

    LinearLayout layout = (LinearLayout)                             
    inflater.inflate(R.layout.activity_etest ,
    null);
    LinearLayout viewGroup = layout;

    Button b1 = new Button(this); 
    b1.setText("test"); 
    viewGroup.addView(b1); 
    viewGroup.addView(new Circle(this));

    }

}

And my class Circle, which extends from View and its method onDraw() consists of:

  ... onDraw(){

  canvas.drawCircle(x, y, radius, paint);

   }

The parameters of drawCircle are not rellevant to this question. I have defined them elsewhere.

I also add the XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button12"
    android:layout_gravity="center_horizontal" />
 </LinearLayout>

Solution

  • create one view group like linearlayout in your xml and using its instance add your dynamic views in that.

    activity_etest.xml

       <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout android:id="@+id/viewg" xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    

    activity

    setContentView(R.layout.activity_etest);
    Linearlayout viewgroup = (LinearLayout)findViewById(R.id.viewg);
    
     Button b1 = new Button(this); 
        b1.setText("test"); 
        viewGroup.addView(b1); 
        viewGroup.addView(new Circle(this));