Android getApplicationContext()不适用于异步事件

Android getApplicationContext()不适用于异步事件,android,Android,我想用一个异步事件(例如,按下按钮)来编辑输入到文本框中的文本。它编译时不会出错,但按下按钮时不会发生任何事情。从我在论坛上收集到的信息来看,我的背景是错误的。有人能帮我吗?代码如下: mSendButton = (Button)findViewById(R.id.button_send); mSendButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { TextVi

我想用一个异步事件(例如,按下按钮)来编辑输入到文本框中的文本。它编译时不会出错,但按下按钮时不会发生任何事情。从我在论坛上收集到的信息来看,我的背景是错误的。有人能帮我吗?代码如下:

mSendButton = (Button)findViewById(R.id.button_send);
mSendButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        TextView view = (TextView)findViewById(R.id.edit_text_out);
        String message = view.getText().toString();
        if (message == "bla") {
            Toast.makeText(getApplicationContext(), "Bla was entered", Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(getApplicationContext(), "Bye ", Toast.LENGTH_SHORT).show();
        }
    }
});

您确定没有堆栈跟踪吗

您的代码似乎是正确的,至少在活动中是这样

建议:

  • 尝试使用getBaseContext()而不是getApplicationContext()
  • 查找堆栈跟踪
  • 尝试Toast.makeText(MyActivityClass.this,“Bye”,Toast.LENGTH\u SHORT.show()
试试这个:

mSendButton = (Button)findViewById(R.id.button_send);
mSendButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        TextView view = (TextView)findViewById(R.id.edit_text_out);
        String message = view.getText().toString();
        if (message == "bla") {
            Toast.makeText(getActivity(), "Bla was entered", Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(getActivity(), "Bye ", Toast.LENGTH_SHORT).show();
        }
    }
});
或:


或者,更好的做法是,只需将
活动
用作
上下文
,而不是尝试
getBaseContext()
(不推荐)或
getApplicationContext()
(确实不推荐)。谢谢,dystroy。我在上面的代码中发现了这个错误。对函数的调用已被屏蔽。因此,它从一开始就没有达到“如果”的说法。
mSendButton = (Button)findViewById(R.id.button_send);
mSendButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        TextView view = (TextView)findViewById(R.id.edit_text_out);
        String message = view.getText().toString();
        if (message == "bla") {
            Toast.makeText(getContext(), "Bla was entered", Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(getContext(), "Bye ", Toast.LENGTH_SHORT).show();
        }
    }
});