简体   繁体   中英

Android studio: No toast message when button is clicked

I made on toast massage that should show up when button is clicked but that doesn't happen

public class CreateEmailActivity extends AppCompatActivity {

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

        Button send = findViewById(R.id.bntSendMail);

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(),"Sending...",Toast.LENGTH_SHORT).show();
            }
        });
    }
    ...
    ...
}

You can try this instead:

public class CreateEmailActivity extends Activity implements View.OnClickListener { 

    //Declare Button 
    Button send; 

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

        //Intialize Button 
        send = (Button) findViewById(R.id.bntSendMail);

        send.setOnClickListener(CreateEmailActivity.this); 

    } 

    @Override 
    public void onClick(View v) {

        switch(v.getId()) { 
            case R.id.bntSendMail: 
                Toast.makeText(this, "Sending...",Toast.LENGTH_SHORT).show();
                break;

        }

    }
}

I think the issue was with how you initialize your button, but by doing it this way you're able to handle more click events in a cleaner way.

尝试

Toast.makeText( CreateEmailActivity.this,"Sending...",Toast.LENGTH_SHORT).show();

Replace getApplicationContext() with context.

public class CreateEmailActivity extends AppCompatActivity {

    private Context context = CreateEmailActivity.this; //Add this

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

            Button send = findViewById(R.id.bntSendMail);

            send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(context,"Sending...",Toast.LENGTH_SHORT).show(); 
                }
            });
        }
        ...
        ...
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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