2014-06-09 26 views
0

所以我有以下代碼。無法訪問fragment_main中的ID標記

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    // Create the adapter that will return a fragment for each of the three 
    // primary sections of the activity. 
    mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager()); 

    savedSearches = getSharedPreferences(SEARCHES, MODE_PRIVATE); 

     // store the saved tags in an ArrayList then sort them 
     tags = new ArrayList<String>(savedSearches.getAll().keySet()); 
     Collections.sort(tags, String.CASE_INSENSITIVE_ORDER); 

     // create ArrayAdapter and use it to bind tags to the ListView 
     adapter = new ArrayAdapter<String>(this, R.layout.list_item, tags); 

     System.out.println(R.id.list); 
     ListView lv = (ListView) findViewById(R.id.list); 
     lv.setAdapter(adapter); 

    // Set up the ViewPager with the sections adapter. 
    mViewPager = (ViewPager) findViewById(R.id.pager); 
    mViewPager.setAdapter(mSectionsPagerAdapter); 

} 

問題是,我實例化後,lv爲空。我知道R.id.list存在,因爲它按預期返回一個int。我相信問題是R.id.list是在R.layout.fragment_main而不是R.layout.activity_main(因爲setContentView將它設置爲R.layout.activity_main)。不過,我需要爲setContentView使用activity_main。有想法該怎麼解決這個嗎?網上大多數地方只是說這是問題,但沒有給出答案。

謝謝。

回答

0

是的,因爲您正在訪問活動未使用的不同佈局的視圖。

解決方案:

1:您可以從fragment_main轉移你的ListView到您的activity_main

2:您可以啓動一個片段,並設置你的fragment_main爲佈局的片段,然後你可以實例化你的ListView。