2014-04-13 108 views
0

我目前还不熟悉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(); 
} 
+0

你可以在你调用setContentView方法的地方提供代码吗? – Zyn

+0

已修改。谢谢参观。 – MawrCoffeePls

+0

啊,这确实有道理,但是我怎样才能从片段的视图层次中找到一个视图?或者我应该将组件定义从片段的xml文件移动到活动的xml文件中? – MawrCoffeePls

回答

5

在你的碎片的布局XML的意见是被夸大到碎片的观层次,这将不会被添加到该活动的层次结构,直到onAttach()回调,所以在Activity的上下文中的findViewById()将在调用onCreate()时返回null。

如果你想保持在该片段中的意见,倒不如叫findViewById()对从片段中的onCreateView()方法返回的视图,移动视图功能,并引用的片段。

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

+0

你是最棒的,男人。我将组件定义移到活动xml文件中,现在我运行得非常完美。谢谢您的帮助。 – MawrCoffeePls