Tab Fragment Tutorial在构建时失败

时间:2015-05-07 19:02:59

标签: android android-fragments

我正在使用this教程自学标签片段。当我粘贴并运行MainActivity时,我收到此错误:

  

引起:java.lang.NullPointerException:尝试调用虚方法' void android.app.ActionBar.setDisplayShowHomeEnabled(boolean)'在null对象引用上               at hss.fragmenttabstutorial.MainActivity.onCreate(MainActivity.java:27)

所以我将Activity更改为ActionBarActivity,并将ActionBar更改为getSupportActionBar,就像许多人建议的那样。现在它由于getSupportActionBar而无法构建,声明"不兼容的类型"。我该怎么办?

这是主要代码:

import android.app.Activity;
import android.os.Bundle;
import android.app.ActionBar;

import android.app.Fragment;
import android.support.v7.app.ActionBarActivity;

public class MainActivity extends ActionBarActivity {

// Declaring our tabs and the corresponding fragments.
ActionBar.Tab bmwTab, fordTab, toyotaTab;
Fragment bmwFragmentTab = new FragmentTab1();
Fragment toyotaFragmentTab = new FragmentTab2();
Fragment fordFragmentTab = new FragmentTab3();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Asking for the default ActionBar element that our platform supports.
    ActionBar actionBar = getSupportActionBar();

    // Screen handling while hiding ActionBar icon.
    actionBar.setDisplayShowHomeEnabled(false);

    // Screen handling while hiding Actionbar title.
    actionBar.setDisplayShowTitleEnabled(false);

    // Creating ActionBar tabs.
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Setting custom tab icons.
    bmwTab = actionBar.newTab().setText("Fragment1");
    toyotaTab = actionBar.newTab().setText("Fragment2");
    fordTab = actionBar.newTab().setText("Fragment3");

    // Setting tab listeners.
    bmwTab.setTabListener(new TabListener(bmwFragmentTab));
    toyotaTab.setTabListener(new TabListener(toyotaFragmentTab));
    fordTab.setTabListener(new TabListener(fordFragmentTab));

    // Adding tabs to the ActionBar.
    actionBar.addTab(bmwTab);
    actionBar.addTab(toyotaTab);
    actionBar.addTab(fordTab);
}

}

1 个答案:

答案 0 :(得分:1)

而不是import android.app.ActionBar使用android.support.v7.app.ActionBar

这确保了与其他支持库的兼容性,包括ActionBarActivity