简体   繁体   English

当用户留下空白 editText 时,如何设置 Toast 消息

[英]How can I set a Toast message when user leaves a blank editText

I have created this Random number game program here the user enter number b/w 1 to 20 and if the user enters higher number than random number, the toast message is showing and also when user enters lower number than random number.我在这里创建了这个随机数游戏程序,用户输入黑白 1 到 20 的数字,如果用户输入的数字大于随机数,则会显示吐司消息,并且当用户输入的数字小于随机数时也会显示。 But how can I set a Toast message when user leaves a blank EditText and presses the button?但是,当用户留下空白的 EditText 并按下按钮时,如何设置 Toast 消息? Please help me.请帮我。

package com.example.higherlowergame;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Random;

public class MainActivity extends AppCompatActivity
{
    int randnum;
    EditText e;

    public void guess(View view)
    {
        int guessnum= Integer.parseInt ( e.getText ().toString () );

        if(e == null)
        {
            Toast.makeText ( this , "Enter a num" , Toast.LENGTH_SHORT ).show ();
        }

        if(guessnum > randnum)
        {
            Toast.makeText ( this , "guess lower num" , Toast.LENGTH_SHORT ).show ();
        }
        else if (guessnum < randnum)
        {
            Toast.makeText ( this , "guess upper num" , Toast.LENGTH_SHORT ).show ();
        }
        else
        {
            Toast.makeText ( this , "yehh Thts the right num ! and try again for new num" , Toast.LENGTH_LONG ).show ();

            Random random=new Random (  );
            randnum=random.nextInt (20)+ 1;
        }
    }

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

        e=(EditText)findViewById ( R.id.et );

        Random random=new Random (  );
        randnum=random.nextInt (20) + 1;
    }
}

When pressing the button, Check for Edittext length greater than zero then continue to the function.按下按钮时,检查 Edittext 长度是否大于零,然后继续执行该功能。

Try below code,试试下面的代码,

  public void guess(View view)
    {
    if (e.getText().toString().length()==0) {
           Toast.makeText ( this , "YOUR MESSAGE FOR EMPTY" Toast.LENGTH_SHORT ).show();
           return;
       }
 }

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

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