找不到符号'Context',android.content.Context

时间:2015-04-30 20:44:22

标签: java android linux

我有以下代码:

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]         ^

有什么建议吗?谢谢!

2 个答案:

答案 0 :(得分:10)

活动中的上下文是通过YourActivity.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();
    }
}

答案 1 :(得分:2)

简短答案:添加此内容

import android.content.Context;