views:

643

answers:

2

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  A: 

your extending AppWidgetProvider. But the method findViewById is not implemted their. FindByViewId() is defined in Activity

http://developer.android.com/intl/de/reference/android/app/Activity.html#findViewById(int)

Roflcoptr
findViewById() is a method provided by the APIs of the Activity and the View classes only.In your onEnabled(..) method you are calling findViewById(..) on "this" the implicit object reference which in your code translates to an object of type AppWidgetProvider.
Samuh
A: 

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.

Steve H
Thanks! I figured it had something to do with working within a widget instead of an activity but couldn't find anything--those links helped me accomplish what I was trying to do.
areyling