android - 如何使用吐司功能?
问题描述
我刚开始学习 Android Studio。我想通过按下小部件上的按钮来显示 toast 通知。但是,使用 getApplicationContext() 函数时会出错。你能告诉我如何解决吗?其他的东西,包括getBaseContext(),都是一样的......错误信息是“无法解析方法”getApplicationContext()“”我不会说英语,所以我用谷歌翻译......我很如果您不能理解,请见谅...
package com.jhjsapp.widget;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;
/**
* Implementation of App Widget functionality.
*/
public class TestWidget extends AppWidgetProvider {
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
CharSequence widgetText = context.getString(R.string.appwidget_text);
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.test_widget);
views.setTextViewText(R.id.appwidget_text, widgetText);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
@Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
@Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
public void butcli(View view){
Toast.makeText(getApplicationContext(),"버튼 눌림", Toast.LENGTH_SHORT).show();
}
}
这是JAVA代码
解决方案
您无法Toast
使用显示消息,getApplicationContext()
因为 Widget 扩展了AppWidgetProvider。因此,您无法获取当前上下文。
你可以尝试这样的事情:
public class testWidget extends AppWidgetProvider{
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, MainPage.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widgetlayout);
views.setOnClickPendingIntent(R.id.button1, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Toast.makeText(context, "Button Clicked", Toast.LENGTH_SHORT).show();
}
推荐阅读
- python - 是否可以自动化彭博终端的任务?
- javascript - 打字稿中的 React HOC 组件给出警告(从非打字稿转换)
- c# - XMLWorkerHelper 不包含在 c# 中采用 0 个参数的构造函数
- java - 如何将我的布局滚动到 android 中的特定文本视图?
- python - 为什么当我尝试创建类的对象时代码显示 SyntaxError: invalid syntax?
- javascript - AJAX 和头/脚更新最佳实践
- flurry - 如何动态创建广告系列?
- sql-server - iis express 上的 web 应用程序的配置问题
- .net - FileStream 缓冲区是否支持不自动刷新的随机写入?
- c# - 如何循环并仅提取标记之间的数据?