findViewById()返回null

时间:2014-04-13 00:47:09

标签: java android

我目前刚接触Android开发,并遇到了以前的研究无法帮助我解决的问题。我在Android活动中使用findViewById()来获取在活动对应的xml片段文件中声明的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。

资源&#34; display_apks&#34;在&#34; fragment_scan_local_apk.xml&#34;中定义。这里:

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

以前提到的网络解决方案已经说过确保在findViewById()上面调用setContentView(),但在我的代码中它是。

有没有人对问题是什么有任何想法?

编辑:根据请求,我在这里调用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();
}

1 个答案:

答案 0 :(得分:5)

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

如果要将视图保留在片段中,最好在片段中的findViewById()方法返回的视图上调用onCreateView(),并移动视图的功能和对片段的引用。

如果您不想/不需要使用片段,可以将fragment_scan_local_apk.xml中的视图移动到activity_scan_local_apk.xml,并保持其余代码不变。如果您决定使用此选项,则可以删除PlaceholderFragment

的代码