findViewById未定义

5

Eclipse将findViewById(int)标记为未定义;它对getResources()也做了同样的事情,但我能够通过调用context.getResources()来解决这个问题(如下所示),似乎找不到类似的解决方案来解决findViewById。以下是代码:

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);
 }

有没有其他需要导入的包来使用findViewById方法?提前感谢。
2个回答

3

当使用AppWidgets时,代码的工作方式有所不同。基本上,您需要使用RemoteView而不是传统的Buttons和findViewByIds。请参阅此类似问题,了解有关如何编写AppWidgets的链接。特别是,这两个链接提供developer.com教程。


谢谢!我想这与在小部件而不是活动中工作有关,但我找不到任何东西——这些链接帮助我完成了我想做的事情。 - areyling

1
你正在扩展 AppWidgetProvider。但是方法 findViewById 没有在那里实现;findViewById 是在 Activity 中定义的。

findViewById()是Activity和View类提供的API中的一种方法。在您的onEnabled(...)方法中,您正在调用findViewById(...)在"this"上,隐式对象引用在您的代码中转换为AppWidgetProvider类型的对象。 - Samuh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接