0

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);
    }
}

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.