带有Fragment和FragmentActivity的TabHost

30

我正在开发一款Android应用程序,希望使用3个选项卡通过每个选项卡上的片段进行导航,但我不知道如何创建这样的结构。

因为每个片段都不同,所以我想单独添加每个片段,但我不知道在FragmentActivity中添加它们的位置。

我有这些文件。

tabs_layout.xml

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

    <TabHost android:id="@android:id/tabhost"
         android:layout_width="match_parent"
         android:layout_height="match_parent">

         <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

             <TabWidget
                android:id="@android:id/tabs" 
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
             />

             <FrameLayout
                 android:id="@android:id/tabcontent" 
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"

             >

                 <FrameLayout
                     android:id="@+id/tabRateAPet" 
                     android:layout_width="match_parent"
                     android:layout_height="match_parent"

                 />

                 <FrameLayout
                     android:id="@+id/tabViewMyRates" 
                     android:layout_width="match_parent"
                     android:layout_height="match_parent"

                 />

                 <FrameLayout
                     android:id="@+id/tabViewGlobalRates" 
                     android:layout_width="match_parent"
                     android:layout_height="match_parent"

                 />


             </FrameLayout>
        </LinearLayout>
    </TabHost>
</LinearLayout>

TabsMain.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

public class MainTabsActivity extends FragmentActivity {
public static final String RATE_A_PET = "Rate a Pet";
public static final String MY_RATES = "My Rates";
public static final String GLOBAL_RATES = "Global Rates";

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabs_layout);
 }
}

Tabs.java

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

public class Tabs extends Fragment implements OnTabChangeListener {
    private static final String TAG = "FragmentTabs";
    public static final String RATE_A_PET = "Rate a Pet";
    public static final String MY_RATES = "My Rates";
    public static final String GLOBAL_RATES = "Global Rates";

    private View mRoot;
    private TabHost mTabHost;
    private int mCurrentTab;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
//      super.onCreateView(inflater, container, savedInstanceState);
        mRoot = inflater.inflate(R.layout.tabs_layout, null);
        mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
        setupTabs();
        return mRoot;
    }

    private void setupTabs() {
        mTabHost.setup(); // important!
        mTabHost.addTab(newTab(RATE_A_PET, R.string.tabRateAPet, R.id.tabRateAPet));
        mTabHost.addTab(newTab(MY_RATES, R.string.tabViewMyRates, R.id.tabViewMyRates));
    }

    private TabSpec newTab(String tag, int labelId, int tabContentId) {
        Log.d(TAG, "buildTab(): tag=" + tag);

        View indicator = LayoutInflater.from(getActivity()).inflate(
                R.layout.tab,
                (ViewGroup) mRoot.findViewById(android.R.id.tabs), false);
        ((TextView) indicator.findViewById(R.id.text)).setText(labelId);

        TabSpec tabSpec = mTabHost.newTabSpec(tag);
        tabSpec.setIndicator(indicator);
        tabSpec.setContent(tabContentId);
        return tabSpec;
    }


    @Override
    public void onTabChanged(String tabId) {
        Log.d(TAG, "onTabChanged(): tabId=" + tabId);
        if (RATE_A_PET.equals(tabId)) {
            updateTab(tabId, R.id.tabRateAPet);
            mCurrentTab = 0;
            return;
        }
        if (MY_RATES.equals(tabId)) {
            updateTab(tabId, R.id.tabViewMyRates);
            mCurrentTab = 1;
            return;
        }
        if (GLOBAL_RATES.equals(tabId)) {
            updateTab(tabId, R.id.tabViewGlobalRates);
            mCurrentTab = 2;
            return;
        }
    }   
    private void updateTab(String tabId, int placeholder) {
        FragmentManager fm = getFragmentManager();
        if (fm.findFragmentByTag(tabId) == null) {
            fm.beginTransaction()
                    .replace(placeholder, new RateMyPetActivity(), tabId)
                    .commit();
        }
    }

}

请看这个教程,如果您遇到任何困难可以问我... http://manishkpr.webheavens.com/android-viewpager-example/ - TheFlash
您也可以参考这个链接。http://wptrafficanalyzer.in/blog/adding-navigation-tabs-containing-listview-to-action-bar-in-android/ - Shadow
2个回答

80

我建议为每个选项卡创建一个单独的片段文件。最近我也这样做了,因此我在下面列出了我的代码:

布局文件

activity_main.xml

<android.support.v4.app.FragmentTabHost
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TabWidget
        android:id="@android:id/tabs"

        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"/>

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="0"/>

    <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

</LinearLayout>
</android.support.v4.app.FragmentTabHost>

tab1_view.xml //使用此格式添加相应的选项卡布局(确保更改字符串变量)

<?xml version="1.0" encoding="utf-8"?>
<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=".DeviceFragment" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tab1_fragment_string" />

</LinearLayout>

SRC文件

MainActivity.java //注意在.addTab过程中,我只使用了文本。你也可以使用图标来添加drawables,这些图标需要添加到您的hdpi文件夹中。在此示例中,我仅创建了三个选项卡。

package com.example.applicationname;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;

public class MainActivity extends FragmentActivity {
    // Fragment TabHost as mTabHost
    private FragmentTabHost mTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),
            Tab1Fragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
            Tab2Fragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("tab3").setIndicator("Tab3"),
            Tab3Fragment.class, null);
    }
}

Tab1Fragment.java //需要为所需的选项卡再次复制

package com.example.applicationname;

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

public class Tab1Fragment extends Fragment  {

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View V = inflater.inflate(R.layout.tab1_view, container, false);

        return V;
    }
}

确保您的 R.java 和 strings.xml 文件正确设置,然后您的选项卡应该可以正常使用。


我们可以像iOS一样将选项卡移动到底部吗? - Dharmendra
@Dharmendra - 我不相信你能够这样做,更重要的是,你不应该尝试这样做,因为Android文档中谈到他们不希望开发者模仿iOS的用户界面。 - Kylie Moden
1
@KylieModen,不错的教程。我正在尝试通过在我的一个片段中包含EditText来进行修改。然而,一旦我尝试在EditText中输入内容,焦点就会回到选项卡(突出显示当前选项卡)。有什么建议吗?谢谢。 - Yehuda Gutstein
2
明白了,如果是碎片的情况下,在tabhost.setup中需要使用getChildFragmentManager()。 - SohailAziz
2
请解释使用tabcontent和realtabcontent即两个框架布局的原因。 - TechSpellBound
显示剩余7条评论

1

TabHost不能保留{{strong}}Fragment的状态{{/strong}}。那么,为什么要使用TabHost呢?

因此,应该使用ViewPagerTabLayout

{{strong}}ViewPager优点{{/strong}}胜过Tabhost:

  • ViewPager可以保留Fragment状态。如果切换了Fragment,它将不会再次创建。
  • 内置滑动功能,为用户提供更流畅的体验。
  • 消耗较少的CPU,因为Tabhost在切换选项卡时会重复创建Fragment/Activity。

看看差别:

使用Tablayout + ViewPager(支持滑动,保留Fragment状态)

Tablayout + ViewPager

使用TabHost(不支持滑动,不保留状态)

TabHost

Tablayout + ViewPager 的小代码

// find views by id
ViewPager viewPager = findViewById(R.id.viewpager);
TabLayout tabLayout = findViewById(R.id.tablayout);

// attach tablayout with viewpager
tabLayout.setupWithViewPager(viewPager);

ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

// add your fragments
adapter.addFrag(new SampleFragment(), "Tab1");
adapter.addFrag(new SampleFragment(), "Tab2");
adapter.addFrag(new SampleFragment(), "Tab3");

// set adapter on viewpager
viewPager.setAdapter(adapter);

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">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

注意 如果您还没有使用AndroidX,则需要在布局中进行以下更改。

  • com.google.android.material.tabs.TabLayout更改为android.support.design.widget.TabLayout
  • androidx.viewpager.widget.ViewPager更改为android.support.v4.view.ViewPager

但我强烈建议迁移到AndroidX,请参见@this answer以了解原因。

这是适用于应用程序中所有Viewpager的通用ViewPagerAdapter

public class ViewPagerAdapter extends FragmentStatePagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

    public void addFrag(Fragment fragment) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add("");
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }
}

重要相关链接


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