简体   繁体   English

带按钮的Android自定义对话框

[英]Android custom dialog with button

Very simple question today. 今天的问题很简单。 When I attempt to retreive a reference to the button on the dialog I always receive a null value. 当我尝试检索对对话框上按钮的引用时,我总是收到一个空值。

@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();
    }



}

Yes the button exists, no I did not mispell it's reference. 是的,该按钮存在,不,我没有拼错它的引用。 Yes I've cleaned the project and restarted eclipse. 是的,我已经清理了项目并重新启动了Eclipse。 How can the button not be associated with the view when i clearly called setContentView()? 当我明确调用setContentView()时,按钮如何不与视图关联? I'm sure it's simple, I've never used dialogs before, new to GUI in general. 我敢肯定这很简单,我以前从未使用过对话框,这是GUI的新功能。 Especially Android 尤其是Android

Button button = (Button)dialog.findViewById(R.id.pinlogin);
                        ^^^^^^

When you show Dialog ,you have to give refrences of dialog .because without it , Button refrences from main.xml .i mean from main view setContentView(R.layout.main); 当显示Dialog时,您必须提供refrences of dialog引用。因为没有它,则Button refrences from main.xml .i是主视图setContentView(R.layout.main); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM