片段布局未在Android中显示

时间:2014-05-12 16:15:49

标签: android android-fragments android-tabhost fragment-tab-host android-nested-fragment

我正在尝试将TabHost添加为Android中Action Bar标签的子标签。 FragmentTabHost已正确添加,我在TabHost的任何标签上的select上添加了片段,但Fragment的布局未显示,我在布局中只有一个TextView Fragment。请问你能问一下这是什么问题吗?

MainFragment.java

public class MainFragment extends Fragment {

    private FragmentTabHost mTabHost;

    @Override
    public View onCreateView(LayoutInflater layoutInflater, ViewGroup conViewGroup, Bundle bundle) {

        mTabHost = new FragmentTabHost(getActivity());
        mTabHost.setup(getActivity(), getChildFragmentManager());

        mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Info"), SubFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Notes"), SubFragment.class, null);

        return mTabHost;
    }
}

SubFragment.java

public class SubFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater layoutInflater, ViewGroup conViewGroup, Bundle bundle) {
        return layoutInflater.inflate(R.layout.fragment_sub_main, conViewGroup, false);
    }
}

MainActivity.java

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    if(tab.getPosition() == 0)
        fragmentTransaction.replace(R.id.container, new MainFragment());
    else
        fragmentTransaction.replace(R.id.container, new MainSecondFragment());
}

fragment_sub_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Android !"
        android:gravity="center"/>

</LinearLayout>

0 个答案:

没有答案