“void is an invalid type for the variable buttonOK” - trying to close dialog after clicking button

前端 未结 3 745
梦谈多话
梦谈多话 2021-01-28 07:08

Some time ago i\'ve made a simple dialog. Everything looks fine, but i\'m meeting troubles after trying to close it. The error is \"void is an invalid type for the variab

相关标签:
3条回答
  • 2021-01-28 07:21

    Since you are trying to use the android:onClick attribute with "buttonOK", you must declare public void buttonOK(View v) {} as a regular method in your class. (Currently you are trying to nest it inside aboutApp(), also understand that you cannot nest methods in Java.)

    public class MyActivity extends Activity {
        Dialog dialog;
    
        public void onCreate(Bundle savedInstanceState) { ... }
    
        public void aboutApp(View view) {
            // custom dialog
            dialog = new Dialog(context);
            ...
        }
    
        // Move your method here:
        public void buttonOK(View v) {
            dialog.dismiss();
        }
    }
    
    0 讨论(0)
  • 2021-01-28 07:24

    Your using dialogs incorrectly. Here's an example for you.

    AlertDialog dialog = new AlertDialog.Builder(this).create();
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            //TODO Handle click here
    
        }
    });
    
    dialog.show();
    
    0 讨论(0)
  • 2021-01-28 07:34

    You have defined a method (buttonOK()) within another method (aboutApp()). This is not possible in Java. The compiler tries to make sense of this and supposes somhow that buttonOk is meant as a variable -- thus the misleading error message.

    0 讨论(0)
提交回复
热议问题