我查看了互联网上关于Android的可滑动标签视图的每个教程。每次我使用不同的代码,它都会崩溃! logcat给出了这个错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void android.app.ActionBar.setNavigationMode(int)' on a null
object reference
我不知道为什么这不起作用。这是我的MainActivity代码:
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private ActionBar actionBar;
private TabsPagerAdapter tabPagerAdapter;
private String[] tabs = {"Missed Calls", "Dialled", "Received"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
tabPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabPagerAdapter);
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
/**
* on swipe select the respective tab
* */
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
答案 0 :(得分:2)
我认为你在这里获得了actionBar的空值:
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
更改为
actionBar = getSupportActionBar();
使用导入:
import android.support.v7.app.ActionBarActivity;
请记住,您必须从ActionBarActivity
public class MainActivity extends ActionBarActivity {
更多信息:
如果您使用支持库
import android.support.v7.app.ActionBarActivity;
public class MainActivity extends ActionBarActivity {
使用
getSupportActionBar()
而不是getActionBar()