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

前端 未结 6 539
陌清茗
陌清茗 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:06

    You can do this quite easy by setting an id on the layout on which you want to add views to. Say your main.xml look like this:

    
      
      
      
    
    

    Lets assume that you want to add your additional views to the LinearLayout with id id/container. In your onCreate method you could retrieve that object for later use:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContainer = (ViewGroup)view.findViewById(R.id.container);
    }
    

    Now you are all set to add other views to your container ViewGroup:

    LinearLayout theButtons = getButtons()
    mContainer.addView(theButtons);
    

    In the getButtons method you need to create your LinearLayout containing the buttons you need. Either you do this programmatically or by inflating a view defined in an XML file. See LayoutInflater.inflate.

提交回复
热议问题