【问题标题】:findViewById() returning nullfindViewById() 返回 null
【发布时间】:2014-04-13 00:47:09
【问题描述】:

我目前是 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。

资源“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();
}

【问题讨论】:

  • 能否提供调用setContentView方法的代码?
  • 已编辑。感谢您的观看。
  • 啊,这确实有道理,但是我怎样才能从片段的视图层次结构中找到视图呢?还是应该将组件定义从片段的 xml 文件移动到活动的 xml 文件?

标签: java android


【解决方案1】:

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

如果要保留Fragment中的View,最好在Fragment中onCreateView()方法返回的View上调用findViewById(),并将View的功能和引用移动到Fragment .

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

【讨论】:

  • 你是最棒的,伙计。我将组件定义移动到活动 xml 文件中,现在我运行良好。感谢您的帮助。
猜你喜欢
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
  • 2016-09-18
  • 1970-01-01
相关资源
最近更新 更多