Heyho。我正在尝试在ActionBar导航中使用标签导航(带有片段),但我无法让它工作!这可能吗?如果不是那就好奇......
这就是我已经得到的:
MainActivity.java
...
import android.app.Fragment;
import android.app.FragmentTransaction;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Fragment fragmentA = new FragmentA();
ActionBar.Tab tabFragmentA = bar.newTab().setText("FragmentA");
tabFragmentA.setTabListener(new MyTabListener(fragmentA));
bar.addTab(tabFragmentA);
Fragment fragmentB = new FragmentB();
ActionBar.Tab tabFragmentB = bar.newTab().setText("FragmentB");
tabFragmentB.setTabListener(new MyTabListener(fragmentB));
bar.addTab(tabFragmentB);
bar.setDisplayShowTitleEnabled(false); // remove top title bar
bar.setDisplayShowHomeEnabled(false);
}
public class MyTabListener implements TabListener {
private Fragment fragment;
public MyTabListener(Fragment fragment) {
this.fragment = fragment;
}
@Override
public void onTabSelected(Tab arg0, FragmentTransaction ft) {
ft.replace(R.id.fragmentContainer, fragment);
}
@Override
public void onTabUnselected(Tab arg0, FragmentTransaction ft) {
}
@Override
public void onTabReselected(Tab arg0, FragmentTransaction ft) {
}
}
}
我从v4支持api尝试了FragmentTabHost,但是当我使用这个时,我想在实例化Fragment时在MainActivity中得到classcasterror。 当我还将MainActivity中的Fragment导入更改为支持api时,我的tablistener不再工作了。那么......我该怎么办?还有其他建议吗?
FragmentA.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
public class FragmentA extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_a, container, false);
FragmentTabHost mTabHost = new FragmentTabHost(getActivity());
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.fragmentAContainer);
return view;
}
}
谢谢你的帮助!