【发布时间】:2011-02-05 15:13:22
【问题描述】:
我在向用 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 并将其添加到此视图中,但我只得到NullPointerExceptions..
任何帮助将不胜感激。谢谢
编辑#1
这是我尝试使用的创建 NullPointerException 和“强制关闭”的方法:
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 代码行。有任何想法吗?再次感谢
【问题讨论】:
-
向我们展示您尝试了什么以及您运行的 logcat,因此我们尝试找出您获得 npe 的原因。无论如何考虑创建一个
screen_temperature.xml布局并在setContentView()中使用它。您也可以通过指定整个包来在 xml 中添加您的自定义视图,而不仅仅是名称(即:<my.package.MyCustomView android:id.../>) -
创建一个线性布局(ll)并将GraphTemp视图对象和按钮对象添加到ll。然后将活动的内容视图设置为ll。即 setContentView(ll);
标签: android button android-activity