【问题标题】:Tab Fragment Tutorial failing on build标签片段教程在构建时失败
【发布时间】:2015-05-07 19:02:59
【问题描述】:

我正在使用this 教程来自学标签片段。当我粘贴并运行 MainActivity 我得到这个错误:

原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void android.app.ActionBar.setDisplayShowHomeEnabled(boolean)” 在 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);
}

}

【问题讨论】:

  • 您的操作栏导入错误。您需要从支持包中导入操作栏

标签: android android-fragments


【解决方案1】:

android.support.v7.app.ActionBar代替import android.app.ActionBar

这确保了与支持库的其余部分(包括 ActionBarActivity)的兼容性。

【讨论】:

  • 因此,当我将其更改为该选项时,我的 TabListener 类(即在 ' toyotaTab.setTabListener(new TabListener(toyotaFragmentTab));' 中)会抱怨。我也更改了那里的库,但现在它不会扩展 ActionBar.TabListener
  • Google 似乎让开发人员难以适应新的设计风格和更新。我也遇到了这个问题,你必须彻底改变ActionBar.TabListener 的工作方式。您可以扩展 AppCompatActivity 并更改很多内容,但现在,我建议您坚持以前的内容。如果你想使用AppCompatActivity,这意味着你需要使用Toolbar而不是ActionBar,我回答了一个问题here,关于如何使用它来更新标签布局。
  • 谢谢!很高兴知道。通常我只会说“去死吧!”并回到折旧的标签。我会看看你的答案,看看它是否对我有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-29
  • 2015-11-10
  • 2016-11-30
  • 2022-11-30
  • 1970-01-01
  • 2021-09-11
  • 2019-01-27
相关资源
最近更新 更多