0
這就是我想要做的:我有一個網站有一些按鈕。該網站連接到我的Android應用程序(通過太空船)。根據我點擊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'將一個Runnable發佈到UI線程。 (新的Runnable(){...});'。 –
仍然得到一個空指針。也許問題不是「setBackground」,而是「findViewById」? –
您應該總是在'onCreate()'中執行所有'findViewById()'並將引用保存爲'Views'作爲成員變量。但那不會解決你的問題,你確定這個ID是正確的嗎?這個佈局是否有你想要的'View'? –