简体   繁体   English

如何从 AlertDialog 显示 Toast?

[英]How to display Toast from AlertDialog?

When the user clicks on the save button, an AlertDialog appears and asks the user to input text for the file name.当用户单击保存按钮时, AlertDialog出现一个AlertDialog并要求用户输入文件名的文本。

If the user clicks the positive button ("Ok") without specifying a name, I want to display a toast which asks them to do so, and keep the AlertDialog open.如果用户在没有指定名称的情况下单击肯定按钮(“确定”),我想显示一个要求他们这样做的吐司,并保持AlertDialog打开状态。 But the toast never displays and the dialog closes.但是吐司永远不会显示并且对话框关闭。

The code for the AlertDialog is here: AlertDialog的代码在这里:

    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    alert.setTitle(R.string.save_game);
    alert.setMessage(R.string.request_name);

    // Set an EditText view to get user input 
    final EditText input = new EditText(this);
    input.setHint(R.string.untitled);
    alert.setView(input);

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
      String value = input.getText().toString();
      if(value != null){
          // Do something with value      
      }
      else{
          Toast.makeText(context, R.string.no_name_given, Toast.LENGTH_SHORT).show();
      }
    }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        // Canceled.
    }
    });

    alert.show();

How can I make this happen?我怎样才能做到这一点?

Thanks!谢谢!

Public void showToast() {
    Toast.makeText(this, R.string.no_name_given, Toast.LENGTH_SHORT).show();
} 

Just call this method instead of displaying toast from an alert dialog box like this in your code.只需调用此方法,而不是在您的代码中显示这样的警告对话框中的 toast。

else {
    showToast();
}

To keep it open use this method要保持打开状态,请使用此方法

public void forceOpen() {

    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    alert.setTitle(R.string.save_game);
    alert.setMessage(R.string.request_name);

    // Set an EditText view to get user input 
    final EditText input = new EditText(this);
    input.setHint(R.string.untitled);
    alert.setView(input);

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String value = input.getText().toString();
            if(value != null) {
                // Do something with value      
            }
            else {
                Toast.makeText(context, R.string.no_name_given, Toast.LENGTH_SHORT).show();
            }
        }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            // Canceled.
        }
    });

    alert.show();

}

Just reopen it.. Not sure why it closes but this will work只需重新打开它.. 不知道为什么它会关闭,但这会起作用

Change the code as follows:更改代码如下:

if(value != null && value.length()>0){

// Do something with value      
 }else{
          Toast.makeText(context, R.string.no_name_given, Toast.LENGTH_SHORT).show();
}

您可以禁用确定按钮。如果条件成立,则再次启用按钮。

public void alert()
    {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.simple, null);

        final EditText etText = (EditText) v.findViewById(R.id.etName);

        final AlertDialog d = new AlertDialog.Builder(this)
        .setView(v)
        .setTitle("Warning ..")
        .setPositiveButton(android.R.string.ok,
                new Dialog.OnClickListener() {
            @Override
            public void onClick(DialogInterface d, int which) 
            {
                //Do nothing here. We override the onclick
                Toast.makeText(getApplicationContext(), "Enter Text", Toast.LENGTH_LONG).show(); 
            }
        })
        .setNegativeButton(android.R.string.cancel, null)
        .create();
        d.show();
}

A simple way what worked for me to get Context from AlertDialog's OnClick method using DialogInterface:使用 DialogInterface 从 AlertDialog 的 OnClick 方法获取上下文的一种简单方法:

((Dialog) dialogInterface).getContext() ((Dialog) dialogInterface).getContext()

Using it in OnClick() method:在 OnClick() 方法中使用它:

public void onClick(DialogInterface dialogInterface, int which) {
        Toast.makeText(((Dialog) dialogInterface).getContext(), "Bla-bla" , Toast.LENGTH_SHORT).show();
}

General Solution通用解决方案

If you want to update anything on Activity from a Dialog this solution might help.如果您想从 Dialog 更新 Activity 上的任何内容,此解决方案可能会有所帮助。 For example, showing a toast message from a Dialog button click.例如,显示来自 Dialog 按钮单击的 Toast 消息。

Create a listener创建监听器

public interface YesNoClickListner {

    public void yesClicked();

    public void noClicked();
}

Pass the interface in your dialog在对话框中传递接口

public class FireMissilesDialog extends DialogFragment {

    private YesNoClickListner listner;

    public FireMissilesDialog(YesNoClickListner listner){
        this.listner = listner;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("This is custom Dialog")
            .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    listner.yesClicked();
                }
            })
            .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    listner.noClicked();
                }
            });
        return builder.create();
    }
}

Implement the listener in your Activity and override methods在您的 Activity 中实现侦听器并覆盖方法

public class MainActivity extends AppCompatActivity implements YesNoClickListner{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FireMissilesDialog fireMissilesDialog = new FireMissilesDialog(this);
        fireMissilesDialog.show(getSupportFragmentManager(),"Dialog");

    }

    @Override
    public void yesClicked() {
        Toast.makeText(this, "Yes Clicked", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void noClicked() {
        Toast.makeText(this, "No Clicked", Toast.LENGTH_SHORT).show();
    }
}

Result:结果:

在此处输入图片说明

This solution may not be exactly what you need to solve this particular question.此解决方案可能不是您解决此特定问题所需的完全解决方案。 But this works in general.但这一般有效。 For example, if you need to update a textView in your Activity on YES button click then just override method this like.例如,如果您需要在 YES 按钮上更新您的 Activity 中的 textView,那么只需覆盖这样的方法即可。

@Override
public void yesClicked() {
   Toast.makeText(this, "Yes Clicked", Toast.LENGTH_SHORT).show();
}

Relevant Link:相关链接:

Full working code 完整的工作代码

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

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