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

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

    I see the error u r doing here

    LinearLayout mainLayout = (LinearLayout) findViewById(R.layout.main);
    

    You r taking the layout as Linearlayout object, you should take the LinearLayout id

    Try this

    LinearLayout lnr = (LinearLayout) findViewById(R.id.LinearLayout01);
    
    Button b1 = new Button(this);
    
    b1.setText("Btn");
    
    lnr.addView(b1);
    

提交回复
热议问题