如何在警告对话框中显示Toast消息?

问题描述 投票:0回答:3

我想编写一个程序,当我单击Ok按钮时,会在toast中显示一条消息,用于单击该警告对话框的Ok按钮。但是,这个案子结果却大相径庭。我不知道应该把什么作为makeText()中的第一个参数。显然'this'不是参数上下文的理想参数。这是我写的代码:

package com.example.spinner;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void click (View v) {
        AlertDialog.Builder ad= new AlertDialog.Builder(this);
        ad.setTitle("Alert Window");
        ad.setIcon(R.drawable.ic_launcher);
        ad.setMessage("This is an alert dialog box");
        MyListener m= new MyListener();
        ad.setPositiveButton("OK", m);
        ad.show();
    }
}

class MyListener implements OnClickListener {

    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(this, "You selected OK", Toast.LENGTH_SHORT).show();
    }
}
android alertdialog toast
3个回答
0
投票

替换这个

Toast.makeText(this, "You selected OK", Toast.LENGTH_SHORT).show();

 Toast.makeText(YourActivity.this, "You selected OK", Toast.LENGTH_SHORT).show();

0
投票
Toast.makeText(MainActivity.this,"You selected ok",Toast.LENGTH_SHORT);

0
投票
 AlertDialog ad= new AlertDialog.Builder(MainActivity.this).create();
    ad.setTitle("Alert Window");
    ad.setIcon(R.drawable.ic_launcher);
    ad.setMessage("This is an alert dialog box");
    ad.setButton("OK", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
             Toast.makeText(MainActivity.this, "You selected OK", Toast.LENGTH_SHORT).show();
                }
            });
    //ad is the object reference
            ad.show();
© www.soinside.com 2019 - 2024. All rights reserved.