设置选项卡图标时出现空指针异常 [英] Getting a null pointer exception when setting up the tab icons
本文介绍了设置选项卡图标时出现空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在选项卡中设置图标,但我不断收到空指针异常.我无法理解为什么会发生这种情况?
I am trying to setup icons in the tabs, but I am keep getting null pointer exception.I am unable to understand as to why is happening?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: starting");
setupNavigationView();
setupViewPager();
}
//Responsible for adding the 3 tabs:camera,main,message
private void setupViewPager(){
SectionPagerAdapter sectionPagerAdapter = new SectionPagerAdapter(getSupportFragmentManager());
sectionPagerAdapter.addFragment(new CameraFragment());
sectionPagerAdapter.addFragment(new MainFragment());
sectionPagerAdapter.addFragment(new MessagesFragment());
ViewPager viewPager = findViewById(R.id.container);
viewPager.setAdapter(sectionPagerAdapter);
TabLayout layout = findViewById(R.id.tabs);
layout.setupWithViewPager(viewPager);
layout.getTabAt(0).setIcon(R.drawable.ic_camera);
layout.getTabAt(1).setIcon(R.drawable.ic_instagram);
layout.getTabAt(2).setIcon(R.drawable.ic_action_name);
}
错误:
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.design.widget.TabLayout$Tab android.support.design.widget.TabLayout$Tab.setIcon(int)' on a null object reference
at android.vishal.instagramclone.MainActivity.MainActivity.setupViewPager(MainActivity.java:47)
at android.vishal.instagramclone.MainActivity.MainActivity.onCreate(MainActivity.java:31)
推荐答案
您遇到这个问题是因为您没有添加标签并尝试设置图标
You are facing this issue because you have not added tabs and try to set icon
//Add tabs icon with setIcon() or simple text with .setText()
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.ic_home));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.ic_profile));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.ic_settings));
欲了解更多详情,请查看以下链接
For further details check the link below
https://gist.github.com/faizsiddiqui/9af9cea9051335e1ad3f
这篇关于设置选项卡图标时出现空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文