0

这没有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);
    }
}
4

2 回答 2

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

在此处输入图像描述

于 2013-07-11T00:28:36.830 回答
1

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

于 2013-07-11T00:23:52.310 回答