【问题标题】:Unable to access id tag in fragment_main [duplicate]无法访问 fragment_main 中的 id 标签 [重复]
【发布时间】:2014-06-09 03:40:39
【问题描述】:

所以我有以下代码。

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。有想法该怎么解决这个吗?网上大部分地方都只是说这是问题,但没有给出答案。

谢谢。

【问题讨论】:

    标签: java android setcontentview


    【解决方案1】:

    是的,它为 null,因为您正在从不同的布局访问视图,而您的 Activity 未使用该视图。

    解决方案:

    1:您可以将您的 ListView 从fragment_main 转移到您的activity_main

    2:您可以启动一个片段并将您的 fragment_main 设置为片段的布局,然后您可以从那里实例化您的 ListView。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 2013-06-12
      相关资源
      最近更新 更多