Android findViewById 未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2896253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
findViewById undefined
提问by areyling
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:
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);
}
Is there another package I need to import for findViewById? Thanks in advance.
我需要为 findViewById 导入另一个包吗?提前致谢。
采纳答案by Steve Haley
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 questionfor links on how to write AppWidgets. In particular, the two links for developer.com tutorials.
当您使用 AppWidgets 时,代码的工作方式有很大不同。本质上,您需要使用 RemoteView 而不是传统的 Buttons 和 findViewByIds。有关如何编写 AppWidget 的链接,请参阅此类似问题。特别是 developer.com 教程的两个链接。
回答by Steve Haley
You're extending AppWidgetProvider
. But the method findViewById
is not implemented there; findViewById
is defined in Activity.
您正在扩展AppWidgetProvider
. 但该方法findViewById
并未在那里实现;findViewById
在Activity 中定义。