【发布时间】:2014-06-28 12:49:45
【问题描述】:
这就是我想要做的:我有一个带有一些按钮的网站。该网站已连接到我的 android 应用程序(通过 spacebrew)。根据我单击 ImageButton 更改的背景的按钮。但是每次我点击一个按钮“setBackground”都会抛出异常。
这是我的代码:
public class MainActivity extends Activity{
ImageButton display;
SpacebrewClient client;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
...
//calls the method "changeDisplay"
client.addSubscriber("changeDisplay", SpacebrewMessage.TYPE_STRING, "changeDisplay");
}
public void changeDisplay(String input){
if(input.equals("topay")){
display = (ImageButton)findViewById(R.id.imageButton1);
display.setBackground(getResources().getDrawable(R.drawable.display_2));
}
...
}
}
我找到了这个可能的解决方案:first answer。但这似乎对我不起作用。 我仍然遇到同样的异常。
编辑: 也尝试了第二种解决方案。现在“setBackground”会抛出 NullPointerException。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
display = (ImageButton)findViewById(R.id.imageButton1);
}
public void changeDisplay(String input){
if(input.equals("topay")){
runOnUiThread(new Runnable() {
public void run() {
display.setBackground(getResources().getDrawable(R.drawable.display_2));
}
});}
【问题讨论】:
-
只能在UI线程中修改UI。您可以使用
display. post(new Runnable() {...});将 Runnable 发布到 UI 线程。 -
仍然得到一个 NullPointer。也许问题不是“setBackground”,而是“findViewById”?
-
您应该始终执行
onCreate()中的所有findViewById()并将对Views的引用保存为成员变量。但这不能解决您的问题,您确定 id 是正确的吗?这个布局有你想要的View吗? -
你的
ImageButton在片段布局中吗?
标签: android view nullpointerexception setbackground