首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法访问fragment_main中的id标记

无法访问fragment_main中的id标记
EN

Stack Overflow用户
提问于 2014-06-09 11:40:40
回答 1查看 54关注 0票数 0

所以我有下面的代码。

代码语言:javascript
运行
复制
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之后,它是null。我知道R.id.list是存在的,因为它会像预期的那样返回一个整数。我认为问题在于R.id.list在R.layout.fragment_main中而不是在R.layout.activity_main中(因为setContentView将其设置为R.layout.activity_main)。但是,我需要为setContentView使用activity_main。有什么办法解决这个问题吗?大多数在线网站只是说这是问题所在,但没有给出答案。

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2014-06-09 11:51:32

是的,它是空的,因为您正在访问来自不同布局的视图,而您的活动没有使用该布局。

解决方案:

1:您可以将fragment_main中的ListView传输到activity_main

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24113375

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档