以编程方式将主LinearLayout和Button添加到Android应用程序

时间:2013-07-11 00:19:43

标签: android

这没有xml。我的问题是为什么按钮没有显示在屏幕上?

我添加了一个带有setContentView的布局并添加了按钮。为什么不显示?

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 个答案:

答案 0 :(得分:3)

这有效:

@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

答案 1 :(得分:1)

传递给LinearLayout和Button的Context是null。您应该传递一个Context实例。 Activity继承自Context,因此您可以传递此而不是null。