android - findViewByID(R.layout.skeleton_activity) 返回 null

标签 android

我正在尝试在骨架应用程序的 OnCreate() 中注册上下文菜单:

/** Called with the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Inflate our UI from its XML layout description.
    setContentView(R.layout.skeleton_activity);

    View v = findViewById(R.layout.skeleton_activity);
    registerForContextMenu(v);      

    // Find the text editor view inside the layout, because we
    // want to do various programmatic things with it.
    mEditor = (EditText) findViewById(R.id.editor);

    // Hook up button presses to the appropriate event handler.
    ((Button) findViewById(R.id.back)).setOnClickListener(mBackListener);
    ((Button) findViewById(R.id.clear)).setOnClickListener(mClearListener);

    mEditor.setText(getText(R.string.main_label));
}

调试器告诉我 findViewById(R.layout.skeleton_activity) 返回 null。

@CommonsWare 对 similar post 的解决方案是等到 onFinishInflate()。然而,在 sample project他提供,似乎他并没有等到 onFinishInflate。

我的问题:

  1. 可以registerForContextMenu()等待 直到 onFinishInflate()?
  2. 如果可以,我该怎么做?

最佳答案

此行不正确,它要求提供 id 而您正在提供布局

View v = findViewById(R.layout.skeleton_activity);

相反,如果你想拥有你的根布局元素的对象,那么给它提供一些 id,然后尝试这样的事情

View v = findViewById(R.id.root_element);

关于android - findViewByID(R.layout.skeleton_activity) 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5100273/

相关文章:

android - 具有依赖项的Android Studio自定义gradle任务- “Could not get unknown property”

android - 广播充电器在 Android O 中断开连接

java - 使用模拟器通过 Retrofit 将我的 REST API 与 Android Studio 连接起来

android - 选择日期后,它显示错误的月份

java - 动态地将textview放在relativelayout android中的另一个 View 之上

android - 如何在android中发送带有电子邮件的批处理?

安卓。在另一个布局上的透明布局

javascript - Android WebView 无法找到 JavaScript 函数

java - 如何在 Eclipse 中仅更改 java 修饰 rune 本颜色?

java - 从 OpenGL ES 开始。使用像素绘图