首页 > 解决方案 > 如何使用吐司功能?

问题描述

我刚开始学习 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代码

在此处输入图像描述

标签: androidsyntax-error

解决方案


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

推荐阅读