【发布时间】: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 文件?