如何在Fragment中添加TabHost

8

我正在尝试在一个片段中添加tabhost,但无论我尝试什么,都无法插入它。 可能我在这里缺少一些基础知识。以下是我的TabFragment类的代码,它返回一个视图。

public class TabFragment extends Fragment{  

    public void onCreate(Bundle savedInstanceState)
    {
       super.onCreate(savedInstanceState);
    }
    private TabHost mTabHost;
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) 
    {
          View view = inflater.inflate(R.layout.tabmain, container, false);
          mTabHost = (TabHost) view.findViewById(android.R.id.tabhost);
          mTabHost.setup();//very important to call this
          TabHost.TabSpec tab = mTabHost.newTabSpec("my tab content");
          tab.setIndicator("my tab content");
          mTabHost.addTab(tab);
      return view;
    }
}

1
这个链接可能会有帮助:http://android.codeandmagic.org/2011/07/android-tabs-with-fragments/ - Triode
不,它们正在使用片段制作选项卡,而那不是我需要的,此外我的一个片段必须是静态的。我只需要想办法插入tabhost即可。 - sohil
@sohil,你解决了吗?我也卡在同一个问题上了。你能帮忙吗?这里有链接:http://stackoverflow.com/questions/28106944/how-to-add-tabhost-with-navigation-drawer?noredirect=1#comment44592501_28106944? - user4050065
@Johnson 我解决了,但是很久以前了,我不太记得我是怎么做到的。抱歉。 - sohil
1个回答

18

从API级别17开始,现在可以实现此功能:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

// This class is the 3rd fragment in my ViewPager, 
// to which I wanted to add 2 tabs....
public class TabHostParentFragment extends Fragment {
private FragmentTabHost mTabHost;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mTabHost = new FragmentTabHost(getActivity());
mTabHost.setup(getActivity(), getChildFragmentManager(), R.layout.my_parent_fragment);

Bundle arg1 = new Bundle();
arg1.putInt("Arg for Frag1", 1);
mTabHost.addTab(mTabHost.newTabSpec("Tab1").setIndicator("Frag Tab1"),
    MyNestedFragment1.class, arg1);

Bundle arg2 = new Bundle();
arg2.putInt("Arg for Frag2", 2);
mTabHost.addTab(mTabHost.newTabSpec("Tab2").setIndicator("Frag Tab2"),
    MyNestedFragment2.class, arg2);

return mTabHost;
}

@Override
public void onDestroyView() {
super.onDestroyView();
mTabHost = null;
}
}

请确保更新您的android-support-v4.jar文件,因为当我通过SDK管理器下载时,它没有自动更新。这会导致getChildFragmentManager()函数无法定义。


最新的android-support-v4库对我也适用。 - kdroider
有没有一种方法可以不使用support.vx库来完成这个任务? - lilott8
@Jamison 在这里看看...你能帮忙吗?http://stackoverflow.com/questions/28106944/how-to-add-tabhost-with-navigation-drawer?noredirect=1#comment44592501_28106944 - user4050065
非常感谢您!您能告诉我如何自定义选项卡吗?我想改变下划线颜色,使文本小写,并改变颜色。 - Nevaeh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接