我目前还不熟悉Android开发,并遇到以前的研究无法帮助我解决的问题。我在Android活动使用findViewById()抢在活动的相应的XML片段文件中声明,像这样一个TextView对象:findViewById()返回null
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方法的地方提供代码吗? – Zyn
已修改。谢谢参观。 – MawrCoffeePls
啊,这确实有道理,但是我怎样才能从片段的视图层次中找到一个视图?或者我应该将组件定义从片段的xml文件移动到活动的xml文件中? – MawrCoffeePls