您知道为什么这会使我的应用程序意外关闭:
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.id_weather);
//getting image form url
try {
ImageView i = (ImageView)findViewById(R.id.weather_icon);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("www.myimageurl.png").getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Button b4=(Button)findViewById(R.id.button_weather10);
b4.setOnClickListener(new View.OnClickListener() {
public void onClick(View l) {
System.out.println("Yeah");
}
});
}
}); 如果我注释掉第二个setOnClickListener,它就可以工作。这就像setOnClick中的SetOnClick不工作一样。
这是我的logcat:
Uncaught handler: thread main exiting due to uncaught exception
java.lang.NullPointerException
at com......MyScreen$2.onClick(MyScreen.java:133)第133行是我单击的第二行
发布于 2012-01-11 06:59:06
我认为如果要从clickListener的声明中调用findViewById(),就必须显式地使用activity.this,如下所示:
Button b4=(Button)YourActivity.this.findViewById(R.id.button_weather10);否则,我认为它将尝试调用OnClickListener类的findViewById()方法,而这个方法并不存在。
似乎您必须多次尝试调用setContentView()。你有
setContentView(R.layout.id_weather);在b2的单击侦听器中。但是如果你还没有设置内容,那么你就没有按钮可以点击了。如果你已经设置了一次内容,那么第二次设置应该会失败。我想你只能调用一次setContentView()。
https://stackoverflow.com/questions/8811507
复制相似问题