java 找不到符号“上下文”,android.content.Context

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29977454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:12:42  来源:igfitidea点击:

Cannot find symbol 'Context', android.content.Context

javaandroidlinux

提问by user3578847

I have the following code:

我有以下代码:

package com.androidtest.notification;

import android.app.Activity;
import android.os.Bundle;
import android.widget;
import android.widget.Toast;
import android.content.Context;

public class activityNotification extends Activity
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Context context = getApplicationContext();
        CharSequence text = "Hello toast!";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
}

I'm trying to compile it using ant on command line '$ ant build', but I keep getting the following error:

我正在尝试在命令行“$ ant build”上使用 ant 编译它,但我不断收到以下错误:

error: cannot find symbol
[javac]         Context context = getApplicationContext();
[javac]         ^

Any suggestions please? Thanks!

请问有什么建议吗?谢谢!

采纳答案by codemirror

Short answer: add this

简短回答:添加这个

import android.content.Context;

回答by Stefano Vuerich

Context in Activity is obtained by YourActivity.this or easier with this

Activity 中的上下文是通过 YourActivity.this 获得的,或者更容易使用 this

package com.androidtest.notification;

import android.app.Activity;
import android.os.Bundle;
import android.widget;
import android.widget.Toast;
import android.content.Context;

public class ActivityNotification extends Activity
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Context context = this; // or ActivityNotification.this
        CharSequence text = "Hello toast!";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(this, text, duration);
        toast.show();
    }
}