我有以下代码:
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] ^
有什么建议吗?谢谢!
答案 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;