所以我有下面的代码。
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。有什么办法解决这个问题吗?大多数在线网站只是说这是问题所在,但没有给出答案。
谢谢。
发布于 2014-06-09 11:51:32
是的,它是空的,因为您正在访问来自不同布局的视图,而您的活动没有使用该布局。
解决方案:
1:您可以将fragment_main中的ListView传输到activity_main中
或
2:您可以开始一个片段并将您的fragment_main设置为该片段的布局,然后您可以从那里实例化您的ListView。
https://stackoverflow.com/questions/24113375
复制相似问题