我在android studio中有一组标签。他们都工作正常,但他们没有显示任何内容,即使他们确实有内容。所以我在这个网站上做了一些挖掘,我找到了这个Problems that users encounter with fragments
所以我按照用户给出的建议。但似乎我的应用程序因为空指针异常而崩溃。请有人帮我发现错误:
的 MainActivity.java
public class MainActivity extends AppCompatActivity implements Photos.OnFragmentInteractionListener, About.OnFragmentInteractionListener, Watch.OnFragmentInteractionListener{
private TabLayout myTabLayOut;
private ViewPager viewPager;
private TabsPagerAdapter tabsPagerAdapter;
public MainActivity()
{
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_content);
myTabLayOut = findViewById(R.id.tabLayout);
myTabLayOut.addTab(myTabLayOut.newTab().setText("Photos"));
myTabLayOut.addTab(myTabLayOut.newTab().setText("About"));
myTabLayOut.addTab(myTabLayOut.newTab().setText("Watch"));
myTabLayOut.setTabGravity(TabLayout.GRAVITY_FILL);
myTabLayOut.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager = findViewById(R.id.pager);
//Item 0 being the photos fragment. Just for testing for the time being. WHERE The error happens
tabsPagerAdapter = new TabsPagerAdapter(tabsPagerAdapter.getItem(0).getTargetFragment(), myTabLayOut.getTabCount());
viewPager.setAdapter(tabsPagerAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(myTabLayOut));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_menu,menu);
return true;
}
@Override
public void onFragmentInteraction(Uri uri) {
}
}
TabsPagerAdapter.java
public class TabsPagerAdapter extends FragmentPagerAdapter {
//A field to hold the number of tabs
private int numberOfTabs;
public TabsPagerAdapter(Fragment fragmentManager, int numberOfTabs)
{
super(fragmentManager.getChildFragmentManager());
this.numberOfTabs = numberOfTabs;
}
//Which item to return depending on the position
@Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new Photos();
case 1:
return new About();
case 2:
return new Watch();
default:
return null;
}
}
@Override
public int getCount() {
return numberOfTabs;
}
}
答案 0 :(得分:0)
你的问题在于这一行:
tabsPagerAdapter = new TabsPagerAdapter(tabsPagerAdapter.getItem(0)...
尝试分配tabsPagerAdapter
的值时,您尝试使用此对象的值NULL
。
答案 1 :(得分:0)
FragmentViewPagers getItem
方法名称具有误导性 - 它不会返回寻呼机中显示的实际片段,它只用于创建一次。如果您尝试调用此方法,您将始终获得一个新项目。