【问题标题】:Cannot find symbol 'Context', android.content.Context找不到符号“上下文”,android.content.Context
【发布时间】:2015-04-30 20:44:21
【问题描述】:

我有以下代码:

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

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

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

有什么建议吗?谢谢!

【问题讨论】:

    标签: java android linux


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      简答:添加这个

      import android.content.Context;
      

      【讨论】:

      • 还有这个?上下文上下文 = getApplicationContext();
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-11
      • 2015-09-06
      • 1970-01-01
      • 2013-09-12
      • 2013-06-06
      相关资源
      最近更新 更多