2012-03-02 72 views
8

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

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 2012-03-02 06:58:54

+0

不,它不。他们正在使用片段制作制表符,那不是我的要求加我的片段之一必须是静态的。我绝对需要以某种方式插入tabhost – sohil 2012-03-03 04:04:06

+0

@sohil你有没有得到解决..我卡在相同..你可以帮助..在这里检查http://stackoverflow.com/questions/28106944/how-to-add-tabhost-与导航抽屉?noredirect = 1个#comment44592501_28106944? – 2015-01-23 13:37:41

回答

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的支持,v4.jar文件,因为它没有自动更新我,当我通过下载SDK经理。这可以防止定义getChildFragmentManger()函数。

+1

谢谢一堆兄弟! – 2013-05-31 07:21:15

+0

这也适用于我使用最新的android-support-v4库。 – kdroider 2013-08-07 06:14:12

+0

非常感谢你 – samira 2014-04-16 05:43:01