Matthew Hoggan
Matthew Hoggan

Reputation: 7594

Programatically Add Main LinearLayout and Button to Android App

There is no xml to this. My question is why does the button not show up on the screen?

I have added a layout with setContentView and added the button. Why does it not show?

package com.my.layoutexample;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout mainLayout = new LinearLayout(null);
        mainLayout.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        mainLayout.setOrientation(LinearLayout.VERTICAL);
        setContentView(mainLayout);

        Button button = new Button(null);
        button.setText("Send");
        button.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT));
        mainLayout.addView(button);
    }
}

Upvotes: 0

Views: 115

Answers (2)

jpardogo
jpardogo

Reputation: 5666

This works:

@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //1 - You need to pass the context to the linear layout constructor
    LinearLayout mainLayout = new LinearLayout(this);

    //The parent layout must MATCH_PARENT
    mainLayout.setLayoutParams(new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT));
    mainLayout.setOrientation(LinearLayout.VERTICAL);
    setContentView(mainLayout);
    //You need to pass the context to the button constructor
    Button button = new Button(this);
    button.setText("Send");
    //I set the button to the size of its text, but you could fill the whole screen (parent) if you want as you where doing
    button.setLayoutParams(new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));
    mainLayout.addView(button);
}

enter image description here

Upvotes: 3

Emmanuel
Emmanuel

Reputation: 13223

The Context you are passing to the LinearLayout and Button is null. You should pass a Context instance. Activity inherits from Context so you can pass this instead of null.

Upvotes: 1

Related Questions