我正在使用带有片段的操作栏标签,但我遇到了麻烦。 我用setNavigationMode(ActionBar.NAVIGATION_MODE_TABS)获取NullPointerException
代码是这样的:
主要活动
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setup action bar for tabs
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
ActionBar.Tab tabInserir = actionBar.newTab().setText("Inserir");
ActionBar.Tab tabListar = actionBar.newTab().setText("Listar");
Fragment FragmentInserir = new InserirFilmeFragment();
Fragment FragmentListar = new ListarFilmeFragment();
tabInserir.setTabListener(new MyTabsListener(FragmentInserir));
tabListar.setTabListener(new MyTabsListener(FragmentListar));
actionBar.addTab(tabInserir);
actionBar.addTab(tabListar);
}
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
//do what you want when tab is reselected, I do nothing
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
ft.replace(R.id.action_bar_container, fragment);
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
}
}
主要活动XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/fragment_placeholder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
INSERIR FRAGMENT
public class InserirFilmeFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_inserir_filme, container, false);
}
}
LISTAR FRAGMENT
public class ListarFilmeFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_listar_filme, container, false);
}
}
任何人都知道我能做什么?