user663467
user663467

Reputation: 59

How do I display a custom dialog box from a function?

In my app, I have three menu options that call functions. One of the three calls a function that is supposed to read some info from a file and then display it in a dialog box. My problem is getting the dialog box to work. I am using http://www.helloandroid.com/tutorials/how-display-custom-dialog-your-android-application as a reference, but the methods they used do not work for me.

The part between the lines of asterisks is where I am getting an error. The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new DialogInterface.OnClickListener(){})" It goes on to list suggested alternatives, which give the same error but list setOnClickListener as a suggested alternative. I get another error after the override: "The method onClick(View) of type new DialogInterface.OnClickListener(){} must override a superclass method"

There has to be an easy way to accomplish this task? Am I missing something that should be obvious?

//now stick it in a dialog box
        Context mContext = getApplicationContext();
        Dialog dialog = new Dialog(mContext);
        dialog.setContentView(R.layout.custom_dialog);
        dialog.setTitle("Totals");
        dialog.setCancelable(true);
        TextView text1 = (TextView) dialog.findViewById(R.id.diagtext1);
        TextView text2 = (TextView) dialog.findViewById(R.id.diagtext2);
        TextView text3 = (TextView) dialog.findViewById(R.id.diagtext3);
        Button btn = (Button) dialog.findViewById(R.id.button);
        text1.setText(dist);
        text2.setText(time);
        text3.setText(speed);
        //******************************************************
        btn.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v){
                finish();
            }

        });
        //******************************************************
        dialog.show();

    }

Upvotes: 1

Views: 1933

Answers (2)

Edy Cu
Edy Cu

Reputation: 3352

Mark/Comment Button 'btn' and try add negative button.

    dialog.setNegativeButton("Quit", new OnClickListener(){
        @Override
        public void onClick(View v){
            finish();
        }

    });

Hopefully help you.

Upvotes: 0

typo.pl
typo.pl

Reputation: 8942

You have to import android.view.View.OnClickListener; to get rid of the first error.

Remove the @Override before the onClick() method. View.OnClickListener declares onClick() as abstract void so there is no implementation to override.

The finish() call in the onClick() method will close your activity/app if there's only one Activity running. You may want to use dialog.dismiss() or dialog.cancel() instead.

Upvotes: 2

Related Questions