今天的问题很简单。当我尝试检索对对话框中按钮的引用时,我总是收到一个空值。
@Override
public void onRestart() {
super.onRestart();
//must prompt with modal dialog for pin
Dialog dialog = new Dialog(this);
dialog.setOwnerActivity(this);
dialog.setCancelable(false);
//check pin
dialog.setCanceledOnTouchOutside(false);
//set view to enterpin XML screen
dialog.setContentView(R.layout.enterpin);
//register button
//show dialog
dialog.show();
//listen for button being clicked
Button button = (Button) findViewById(R.id.pinlogin);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
EditText editText = (EditText) findViewById(R.id.enterpin);
int enteredPin = Integer.parseInt(editText.getText().toString());
SharedPreferences sharedP = getPreferences(MODE_PRIVATE);
int temp = sharedP.getInt("pin", 0);
if(enteredPin==temp){
pinCheck = true;
}else{
pinCheck = false;
}
}
});
if(pinCheck){
dialog.dismiss();
}
}
是的,按钮存在,不,我没有拼错它的引用。是的,我已经清理了项目并重新启动了 Eclipse。明明调用了setContentView(),按钮怎么会不关联 View 呢?我敢肯定这很简单,我以前从未使用过对话框,一般来说是 GUI 的新手。尤其是安卓
最佳答案
Button button = (Button)dialog.findViewById(R.id.pinlogin);
^^^^^^
当您显示对话框时,您必须提供对话框的引用
。因为没有它,来自 main.xml 的按钮引用
。我的意思是从主视图 setContentView (R.layout.main);
.
关于java - 带按钮的Android自定义对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10997273/