[Android] 以编程方式向布局添加按钮


Answers

如果您只是在setContentView内的onCreate()开头包含了一个布局文件,并希望以编程方式添加新元素,请尝试以下方法:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

然后你可以创建一个新的Button例子,然后添加它:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);
Question

我在向XML创建的布局中添加按钮时遇到了问题。 这是我想要实现的目标:

//some class
else {
        startActivity(new Intent(StatisticsScreen.this, ScreenTemperature.class));
}
////

//ScreenTemperatureClass
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //this is where I call another class that
    //displays a nice graph
    setContentView(new GraphTemperature(getApplicationContext()));

}

我想在这个新屏幕上添加一个Button ,使其显示在图表下方。 我已经尝试创建一个LinearLayout视图,然后创建一个Button并将其添加到此视图但我只是得到NullPointerException ..

任何帮助,将不胜感激。 谢谢

编辑#1

以下是我尝试使用的创建NullPointerException和'force close'的内容:

Button buybutton;
LinearLayout layout;

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

    setContentView(new GraphTemperature(getApplicationContext()));

    layout = (LinearLayout) findViewById(R.id.statsviewlayout);
    Button buyButton = new Button(this);
    buyButton.setText(R.string.button_back);
    buyButton.setLayoutParams(new LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    layout.addView(buyButton);

}

这是logcat错误:

ERROR/AndroidRuntime(293): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.weatherapp/com.weatherapp.ScreenTemperature}: java.lang.NullPointerException
ERROR/AndroidRuntime(293):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
ERROR/AndroidRuntime(293):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
ERROR/AndroidRuntime(293):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
ERROR/AndroidRuntime(293):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)

在logcat中显然有更多关于这个错误的行,不确定你是否想要它?

编辑#2

所以我尝试了bhups方法:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GraphTemperature GT = new GraphTemperature(getApplicationContext());             
    layout = (LinearLayout) findViewById(R.id.statsviewlayout);
    Button buyButton = new Button(this);
    buyButton.setText(R.string.button_back);
    buyButton.setLayoutParams(new LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    layout.addView(GT); // line 27
    layout.addView(buyButton);       
    setContentView(layout);           
}

此方法产生与上面相同的logcat错误NullPointerException ,表明它与行号有关。 27这是layout.addView代码行。 有任何想法吗? 再次感谢






Links