Search code examples
javaandroid-studiotoast

How i can show a toast message only one time per click for the current activity


How i can show a toast message only one time per click for the current activity i mean when a user click my button at the first time it shows a toast message but when he click again no toast message appear again


Solution

  • You could use a boolean variable and attach it to an if statement and set it to false. Once the button is clicked set it to true. In the if statement add it like this if(booleanVar==false){YOURTOAST;booleanVar=true}. To briefly explain this, the booleanVar is your switch, you can turn it true(on) or false(off)...

    Edit:

    import android.app.Activity
    import android.os.Bundle;
    import android.widget.Button;
    import android.widget.Toast;
    import android.content.Context;
    
    public class MainActivity extends Activity{
        public static boolean booleanVar = false;
    
        @Override
        protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            Button yourButton = (Button) findViewById(R.id.yourBtn);
            yourButton.setOnClickListener(new View.OnClickListener(){
            public void OnClick(View v){
                if(booleanVar==false){
                    Toast yourToast = Toast.makeText(getApplicationContext(), "YOURTEXT", Toast.LENGTH_SHORT);
                    yourToast.show();
                    booleanVar=true;
                }
            }
        }
    }