0

前段时间我做了一个简单的对话框。一切看起来都很好,但是在尝试关闭它后我遇到了麻烦。错误是 "void is an invalid type for the variable buttonOK"

嗯,我最好给个截图链接:http: //i.imgur.com/tiAiI.png

对话框代码:

public void aboutApp(View view) {

    // custom dialog
                final Dialog dialog = new Dialog(context);
                dialog.setContentView(R.layout.aboutapp);
                dialog.setTitle("about  ");

                // set the custom dialog components - text, image and button
                TextView text = (TextView) dialog.findViewById(R.id.text);
                text.setText("bla bla bla ");
                ImageView image = (ImageView) dialog.findViewById(R.id.image);
                image.setImageResource(R.drawable.android);



                    @Override
                    public void buttonOK(View view) {
                        dialog.dismiss();
                    }


                dialog.show();
}

我应该怎么做才能使它起作用?

PS我有错误public void buttonOK(View view),例如view-Duplicate local variable view我应该重命名它view2吗?

好的,我找到了解决方案。

问题是(正如RidcullybuttonOK()所注意到的)在另一种方法中定义了方法aboutApp(),这是在 java 中无法完成的(uach,现在我知道了:D)。

我只是替换了代码:@Override public void buttonOK(View view) { dialog.dismiss(); }

至:

Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
                // if button is clicked, close the custom dialog
                dialogButton.setOnClickListener(new OnClickListener() {
                    public void onClick(View view2) {
                        dialog.dismiss();
                    }
                });

现在它可以工作了,谢谢大家的帮助!

4

3 回答 3

3

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.

于 2012-09-27T17:18:27.827 回答
1

您错误地使用对话框。这是给你的一个例子。

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();
于 2012-09-27T17:28:52.603 回答
0

由于您尝试将android:onClick属性与 一起使用"buttonOK",因此您必须在类中声明public void buttonOK(View v) {}为常规方法。(目前你正在尝试将它嵌套在里面aboutApp(),也明白你不能在 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();
    }
}
于 2012-09-27T18:01:42.560 回答