Android Studio:单击按钮时无吐司消息

时间:2019-05-22 13:02:47

标签: java android toast

我做了吐司按摩,当单击按钮时应该会出现

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();
            }
        });
    }
    ...
    ...
}

3 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

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;

        }

    }
}

我认为问题在于如何初始化按钮,但是通过这种方式,您可以以更简洁的方式处理更多点击事件。

答案 1 :(得分:0)

尝试

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

答案 2 :(得分:0)

用上下文替换getApplicationContext()。

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(); 
                }
            });
        }
        ...
        ...
    }