我目前刚接触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);
}
Run Code Online (Sandbox Code Playgroud)
在此行抛出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"/>
Run Code Online (Sandbox Code Playgroud)
以前提到的Web解决方案已经说过确保在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();
}
Run Code Online (Sandbox Code Playgroud)
Fragment的布局xml中的视图正在膨胀到Fragment的View层次结构中,在onAttach()回调之前不会将其添加到Activity的层次结构中,因此findViewById()在Activity的上下文中,在onCreate()调用时将为这些视图返回null .
如果要将视图保留在片段中,最好调用findViewById()从onCreateView()片段中的方法返回的视图,并将视图的功能和参考移动到片段.
如果你不希望/需要使用片段,则可以在移动浏览fragment_scan_local_apk.xml到activity_scan_local_apk.xml,并保持代码的其余部分,因为它是.如果您决定使用此选项,则可以删除该代码PlaceholderFragment.