Несовместимые типы: виджет не может быть преобразован в контекст - PullRequest
0 голосов
/ 12 января 2020

Я занимаюсь разработкой виджета и пытаюсь динамически добавить кнопку в мой LinearLayout. Я пытаюсь использовать код из этой темы .

Button myButton = new Button(this);
myButton.setText("Push Me");

LinearLayout ll = (LinearLayout)findViewById(R.id.widget_layout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);

Проблема в том, что я получаю эту ошибку:

error: incompatible types: Widget cannot be converted to Context
        Button myButton = new Button(this);
                                     ^ 

Знаете ли вы, в чем проблема Вот? Мой класс виджетов:

package com.fxteam.malcome;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Button;

import android.view.View;
import android.widget.LinearLayout;

import android.util.Log;

public class Widget extends AppWidgetProvider {

    private static final String SYNC_CLICKED    = "malcome_widget_button";

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        for (int appWidgetId : appWidgetIds) {
            Intent intent2 = new Intent(context, MainActivity.class);
            intent2.putExtra("accountID", "0");
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent2, 0);
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.simple_app_widget);
            views.setOnClickPendingIntent(R.id.malcome_widget_button, pendingIntent);
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }



        Button myButton = new Button(this);
        myButton.setText("Push Me");

        LinearLayout ll = (LinearLayout)findViewById(R.id.widget_layout);
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        ll.addView(myButton, lp);
    }
}

Все ошибки:

BUILD FAILED in 1s
(node:660) UnhandledPromiseRejectionWarning: Error: cmd: Command failed with exit code 1 Error output:
C:\Users\Adam\cordova\widget\malcomeWidget\platforms\android\app\src\main\java\com\fxteam\malcome\Widget.java:47: error: incompatible types: Widget cannot be converted to Context
        Button myButton = new Button(this);
                                     ^
C:\Users\Adam\cordova\widget\malcomeWidget\platforms\android\app\src\main\java\com\fxteam\malcome\Widget.java:50: error: cannot find symbol
        LinearLayout ll = (LinearLayout)findViewById(R.id.widget_layout);
                                        ^
  symbol:   method findViewById(int)
  location: class Widget
C:\Users\Adam\cordova\widget\malcomeWidget\platforms\android\app\src\main\java\com\fxteam\malcome\Widget.java:51: error: cannot find symbol
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        ^
  symbol:   class LayoutParams
  location: class Widget
C:\Users\Adam\cordova\widget\malcomeWidget\platforms\android\app\src\main\java\com\fxteam\malcome\Widget.java:51: error: cannot find symbol
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
                              ^
  symbol:   class LayoutParams
  location: class Widget
C:\Users\Adam\cordova\widget\malcomeWidget\platforms\android\app\src\main\java\com\fxteam\malcome\Widget.java:51: error: cannot find symbol
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
                                           ^
  symbol:   variable LayoutParams
  location: class Widget
C:\Users\Adam\cordova\widget\malcomeWidget\platforms\android\app\src\main\java\com\fxteam\malcome\Widget.java:51: error: cannot find symbol
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
                                                                      ^
  symbol:   variable LayoutParams
  location: class Widget
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\Users\Adam\cordova\widget\malcomeWidget\platforms\android\app\src\main\java\org\apache\cordova\file\AssetFilesystem.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
6 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
    at ChildProcess.whenDone (C:\Users\Adam\cordova\widget\malcomeWidget\platforms\android\cordova\node_modules\cordova-common\src\superspawn.js:169:23)
    at ChildProcess.emit (events.js:210:5)
    at maybeClose (internal/child_process.js:1021:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
(node:660) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:660) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Я прошу прощения за столь много кода в этом вопросе, но я хочу, чтобы он был максимально подробным.

1 Ответ

1 голос
/ 12 января 2020

Вы передали Widget экземпляр вместо действия context, чтобы создать Button.

Использовать

Button myButton = new Button(context);

Вместо

Button myButton = new Button(this);
...