Adam
Adam

Reputation: 9049

added button programmatically to layout, but not appearing

Looking at various examples, below is what seems to be the correct way of adding a view to a layout. However, nothing shows up for me. I'm assuming it has something to do with the layout options, but I'm new so I don't know what is missing.

public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.songs_layout);
            LinearLayout layout = (LinearLayout) View.inflate(this, R.layout.songs_layout, null);

            Button myButton = new Button(this);
            myButton.setText("Change View");
            myButton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            layout.addView(myButton);


        }

Upvotes: 1

Views: 1404

Answers (3)

dsalaj
dsalaj

Reputation: 3207

Solution for Fragment context with Kotlin: In Fragment where the view is inflated in onCreateView the solution is a bit different. The inflated layout is returned:

class MyFragment : Fragment()
    {
    lateinit var v: View

    override fun onCreateView(inflater: LayoutInflater,
                          container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
        v = inflater.inflate(R.layout.my_layout, container, false)
        // ...
        return v
    }
}

In this case, it might be confusing that fetching the parent of the buttons with findViewById and adding the buttons to this view would not work:

val buttonsParent = v.findViewById<LinearLayout>(R.id.buttons_parent)
buttonsParent.addView(myButton)

Instead what you need to do is add the buttons directly with following syntax:

v.buttons_parent.addView(myButton)

Upvotes: 0

DeeV
DeeV

Reputation: 36035

You're not setting the button to the layout that's displayed. You're inflating a new layout and adding the button to that one. Move setContentView() to after layout.addView(myButton), then change it to setContentView(layout).

Upvotes: 0

skynet
skynet

Reputation: 9908

Your layout variable is not the same as the layout you used in setContentView. Try calling setContentView(layout); after layout.addView(myButton); and removing the previous call to it (setContentView(R.layout.songs_layout);).

To be more clear, your onCreate method should look like

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout layout = (LinearLayout) View.inflate(this, R.layout.songs_layout, null);

    Button myButton = new Button(this);
    myButton.setText("Change View");
    myButton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    layout.addView(myButton);
    setContentView(layout);
}

Upvotes: 2

Related Questions