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

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

    just try this:

    LinearLayout mainLinearLayout = (LinearLayout) findViewById(R.layout.llmain);
    

    now create button dynamically like this

     Button btn1 = new Button(this);
     btn1.setText=("Button 1");
     mainLinearLayout .addView(btn1);
    

    now if you want to add onether linearlayout then add it below button then

     LinearLayout llinner = new LinearLayout(this);
    
     Button btn2 = new Button(this);
     btn2.setText=("Button 2");
    mainLinearLayout .addView(btn2);
    
    llinner.addView(btn2 );
    
    mainLinearLayout .addView(llinner);
    

提交回复
热议问题