How to add a button control to an android xml view at runtime?

前端 未结 6 521
陌清茗
陌清茗 2020-12-11 16:26

I have an android xml layout, main.xml. I would like to add controls to this layout at runtime (I would like to add a series of additional linear layouts that contain button

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 17:28

    Ok, I have got it to work.

    The steps are the following: First inflate the xml layout, ie,

    View view = View.inflate(this, R.layout.main, null);
    

    Then instantiate the container object from the xml layout into a ViewGroup class, ie,

    ViewGroup container = (ViewGroup) view.findViewById(R.id.myContainer);
    

    Then create a linearLayout object, create and add onto that any controls needed, add the linearLayout to the container object and use setContentView on the view object, ie,

    container.addView(buttonsLayout);
    this.setContentView(view);
    

提交回复
热议问题