我有带有 ViewPager 的 TabLayout 包括 3 个选项卡/片段。
每次恢复时,我都需要向每个片段添加操作。使用触摸更改片段时一切正常,但是当我以编程方式更改选项卡时,应用程序崩溃。我应该怎么做才能防止这个问题?
这是一些代码来解释我的问题。
private TabLayout tabLayout;
@Override
public void onResume() {
super.onResume();
//This part works when first tab is selected
int chatSelTab = 0;
TabLayout.Tab selectedTab = tabLayout.getTabAt(chatSelTab);
selectedTab.select();
}
private void setupTablayout() {
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.persons)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.groups)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.online)));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount(), this);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
Voids.savePreferences(getApplicationContext(), Voids.CHAT_SELECTED_TAB, tab.getPosition());
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 1:
/* TODO: app crashes here when programmatically select tab nro 1. */
SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout) activity.findViewById(R.id.swipeRefresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// DO MY STUFF
}
});
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
这就是我对 logcat 的了解
08-25 01:20:45.054 31753-31753/com.myapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.myapp, PID: 31753
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.SwipeRefreshLayout.setOnRefreshListener(android.support.v4.widget.SwipeRefreshLayout$OnRefreshListener)' on a null object reference