findViewById undefined

2020-04-07 04:20发布

问题:

Eclipse is marking findViewById(int) as undefined; it was doing the same thing for getResources(), but I was able to get around that by calling context.getResources() instead (as seen below) and can't seem to find a similar workaround for findViewById. Here is the code:

package com.myapp.android.MyWidget;

import android.appwidget.AppWidgetProvider;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Button;
import android.os.Bundle;

public class MyWidget extends AppWidgetProvider {
 private static String[] states;

 @Override
 public void onEnabled(Context context) {
  final Button button = (Button) findViewById(R.id.widget_state_button);

  states = context.getResources().getStringArray(R.array.states);
 }

Is there another package I need to import for findViewById? Thanks in advance.

回答1:

The code works rather differently when you're using AppWidgets. Essentially you need to be working with RemoteView rather than traditional Buttons and findViewByIds. See this similar question for links on how to write AppWidgets. In particular, the two links for developer.com tutorials.



回答2:

You're extending AppWidgetProvider. But the method findViewById is not implemented there; findViewById is defined in Activity.