java - findViewById() 返回 null

标签 java android

我目前是 Android 开发新手,遇到了以前的研究无法帮助我解决的问题。我在 Android Activity 中使用 findViewById() 来获取 Activity 相应 xml fragment 文件中声明的 TextView 对象,如下所示:

public void scanLocalApk() {
    //get the list of apks in the default downloads directory
    ArrayList<File> foundAPKs = findApksInDownloadDirectory();
    //display the list of found apks
    String apkListString = "";
    if (foundAPKs != null)
        for (File f : foundAPKs)
            apkListString += (f.getName() + "\n"); 
    TextView displayApksTextView = (TextView) findViewById(R.id.display_apks);
    displayApksTextView.setText(apkListString);
    TextView apkToInstallTextView = (TextView) findViewById(R.id.label_apk_to_install);
    apkToInstallTextView.setVisibility(View.VISIBLE);
    EditText apkToInstallEditText = (EditText) findViewById(R.id.apk_to_install);
    apkToInstallEditText.setVisibility(View.VISIBLE);
}

此行抛出 NullPointerException: displayApksTextView.setText(apkListString); 因为上面一行中的 findViewById 调用返回 null。

资源“display_apks”在“fragment_scan_local_apk.xml”中定义:

<TextView android:id="@+id/display_apks"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

之前提到的网络解决方案都说要确保 setContentView() 在 findViewById() 之上调用,但在我的代码中确实如此。

有人知道问题出在哪里吗?

编辑:根据请求,我在这里调用 setContentView()

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan_local_apk);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }

    //branch to a logic method
    scanLocalApk();
}

最佳答案

Fragment 的布局 xml 中的 View 将被扩充到 Fragment 的 View 层次结构中,直到 onAttach() 回调之前,该 View 不会添加到 Activity 的层次结构中,因此 findViewById() 在 Activity 上下文中,在调用 onCreate() 时,这些 View 将返回 null。

如果您想将 View 保留在 Fragment 中,最好对从 onCreateView() 方法返回的 View 调用 findViewById() Fragment,并将 View 的功能和引用移至 Fragment。

如果您不想/不需要使用Fragments,可以将fragment_scan_local_apk.xml中的View移动到activity_scan_local_apk.xml,并保留其余代码就这样。如果您决定使用此选项,则可以删除 PlaceholderFragment 的代码。

关于java - findViewById() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23037884/

相关文章:

java - 无法解析方法 findViewByID

Android - 应用程序在 Pre-Lollipop 设备上崩溃

android - 在 Android Studio 中,为什么 build.gradle 的选项卡显示 'app'

java - 如何通过互联网获取地理数据?

java - Eclipse maven编译器不支持编译器插件compilerArgs

java - 我想拆分字符串类型列表并将它们存储在android中的两个不同列表中

android - 如何删除以前的 SavedInstanceState?

java - 如何使用Java代码从具有嵌套数据的Json数组中获取值

Java、 native 应用程序和全局路径

android - 如何使用我的应用程序在 MS-Excel 或 MS-Word 中打开 excel、doc 文件 - Android