Android: programmatically adding buttons to a layout

前端 未结 5 2089
梦如初夏
梦如初夏 2020-11-29 07:40

I\'m trying to get an add button to add another button to the layout, based on the edittext to the left of the button. The point is for a person to list the rooms in their

5条回答
  •  野性不改
    2020-11-29 08:06

    I would add an id to your LinearLayout in xml:

    
    

    And then change your onClick to this:

    public void onClick(View v) {
        switch (v.getId()) {
    
        case R.id.btnAddARoom:
            //add a room
            //Find you parent layout which we'll be adding your button to:
            LinearLayout layout = (LinearLayout) findViewById(R.id.llContainer);
    
            roomName = etAddARoom.getText().toString();
            Button createdButton = new Button(this);
            createdButton.setText(roomName);
            createdButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,         LayoutParams.WRAP_CONTENT));
            layout.addView(createdButton);
    
            //if no rooms make tvnorooms disappear
    
            break;
        }
    }
    

提交回复
热议问题