我必须使用什么方法而不是应用程序小部件中的 findViewById ?

use*_*790 6 android android-widget

当我使用时findViewById(),我收到一个错误。
我应该使用什么方法,而不是findViewById()在我的应用程序小部件中?

PS:我想做这样的事情:

 Button a = (Button) findViewById(R.id.button);
Run Code Online (Sandbox Code Playgroud)

在我的屏幕小部件中

Fax*_*yev 5

您不需要在 Widget 中使用 findViewById() 只需执行此操作

创建一个静态变量,它将作为您的 onClick 名称标签:

private static final String MyOnClick = "Button OnClick";
Run Code Online (Sandbox Code Playgroud)

将此 onClick 标记设置为您的视图,如下所示:

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main);
views.setTextViewText(R.id.your_button, "Button Name");
views.setOnClickPendingIntent(R.id.your_button, MyOnClick);
Run Code Online (Sandbox Code Playgroud)

获取按钮点击侦听器,如下所示

public void onReceive(Context context, Intent intent) {

if (MyOnClick.equals(intent.getAction())){
    //your onClick action is here
  }
};
Run Code Online (Sandbox Code Playgroud)

这里是总代码

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;

public class Widget extends AppWidgetProvider {
    private static final String SYNC_CLICKED    = "automaticWidgetSyncButtonClick";

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        RemoteViews remoteViews;
        ComponentName watchWidget;

        remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        watchWidget = new ComponentName(context, Widget.class);

        remoteViews.setOnClickPendingIntent(R.id.sync_button, getPendingSelfIntent(context, SYNC_CLICKED));
        appWidgetManager.updateAppWidget(watchWidget, remoteViews);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        super.onReceive(context, intent);

        if (SYNC_CLICKED.equals(intent.getAction())) {

            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

            RemoteViews remoteViews;
            ComponentName watchWidget;

            remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
            watchWidget = new ComponentName(context, Widget.class);

            remoteViews.setTextViewText(R.id.sync_button, "TESTING");

            appWidgetManager.updateAppWidget(watchWidget, remoteViews);

        }
    }

    protected PendingIntent getPendingSelfIntent(Context context, String action) {
        Intent intent = new Intent(context, getClass());
        intent.setAction(action);
        return PendingIntent.getBroadcast(context, 0, intent, 0);
    }
}
Run Code Online (Sandbox Code Playgroud)