[英]Android Button: always error when add ClickEvent
我從布局創建了一個按鈕,它工作正常(測試時顯示在屏幕上)。 當我為此Button
添加click事件時,我總是會收到NullPointerException
(您可以在下面的代碼中看到):
Button b1;
int REQUEST_CODE =1;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
b1 = (Button) findViewById(R.id.web_button);
b1.setOnClickListener(new OnClickListener() { //ERROR THIS LINE
public void onClick(View arg0){}
});
setContentView(R.layout.intent);
}
你應該setContentView
第一-在使用前findViewById
-否則它不知道去哪里尋找你的按鈕。
使用以下順序:
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.intent);
b1 = (Button) findViewById(R.id.web_button);
b1.setOnClickListener(new OnClickListener() { //ERROR THIS LINE
public void onClick(View arg0){
}
});
}
在設置內容視圖之前,您正在搜索Button
。 您必須這樣做:
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.intent);
b1 = (Button) findViewById(R.id.web_button);
b1.setOnClickListener(new OnClickListener() { //ERROR THIS LINE
public void onClick(View arg0){
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.