1. 程式人生 > >【Android】 FragmentTabHost+Fragment實現多標籤頁

【Android】 FragmentTabHost+Fragment實現多標籤頁

Android TabHost多標籤頁幾乎是所有APP中必備的控制元件,如通迅錄的【撥號、通話記錄、聯絡人】,微信的【聊天、聯絡人、發現】,如下圖


Android API13之後官方就不推薦使用TabActivity了,取而代之的是FragmentActivity+FragmentTabHost+Fragment的組合

大致用法

要顯示多標籤頁的Activity繼承FragmentActivity,裡面定義一個FragmentTabHost型別的物件,

另外定義幾個類繼承Fragment,實現每個Tab的具體功能並載入對應介面佈局

然後用FragmentTabHost的addTab方法將Fragment新增到FragmentTabHost中顯示,可以點選切換多個Fragmen(即每個標籤頁)

最後再為MainActivity新增滑動手勢來切換標籤頁

寫了個Demo,

MainActivity的主要程式碼:

public class MainActivity extends FragmentActivity{

    private FragmentTabHost mTabHost;
    private LayoutInflater layoutInflater;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        layoutInflater=LayoutInflater.from(this);
        mTabHost=(FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(),R.id.realtabcontent);
        mTabHost.addTab(mTabHost.newTabSpec("首頁").setIndicator("首頁"),FragmentPage1.class,null);
        mTabHost.addTab(mTabHost.newTabSpec("聊天").setIndicator("聊天"),FragmentPage2.class,null);
        mTabHost.addTab(mTabHost.newTabSpec("發現").setIndicator("發現"),FragmentPage3.class,null);
        mTabHost.addTab(mTabHost.newTabSpec("其他").setIndicator("其他"),FragmentPage4.class,null);

    }
}

首先獲取tabhost,然後setup 注意mTabHost和setup()引數的id為安卓自帶ID,這一點在寫佈局檔案時也要注意 setIndicator指定標籤頁的顯示label,可以用字串也可以用自定義的View顯示 對應的佈局檔案為activity_main.xml:
<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="${packageName}.${activityClass}" >

    <FrameLayout 
        android:id="@+id/realtabcontent"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"/>
    
    <android.support.v4.app.FragmentTabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">       
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp" 
            android:layout_height="0dip"
            android:layout_weight="0"/>      
    </android.support.v4.app.FragmentTabHost>
</LinearLayout>

FragMentPage1.Java的原始碼

public class FragmentPage1 extends Fragment{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_page1, null); 
    }
}

因為標籤頁中沒有多餘功能,所以程式碼只加載佈局顯示就好 佈局檔案為fragment_page1.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:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="page1"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

FragmentPage2、3、4與FragmentPage1一致,此處不再給出

這樣四個標籤頁就生成了

最後為Tab新增滑動切換的功能

  • MainActivity實現OnGestureListener介面,
  • 定義一個GestureDetector物件來處理手勢事件
  • 並重載onFling方法處理滑動事件,計算兩次getX()的位置來判斷滑動方向
  • 注意,onTouchEvent方法也要過載,不然沒法獲取觸控事件滑動事件自然也就無效了

修改後的MainActivity原始碼:

public class MainActivity extends FragmentActivity implements OnGestureListener{

    private GestureDetector  mDetector;
    private FragmentTabHost mTabHost;
    private LayoutInflater layoutInflater;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        layoutInflater=LayoutInflater.from(this);
        mTabHost=(FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(),R.id.realtabcontent);
        mTabHost.addTab(mTabHost.newTabSpec("首頁").setIndicator("首頁"),FragmentPage1.class,null);
        mTabHost.addTab(mTabHost.newTabSpec("聊天").setIndicator("聊天"),FragmentPage2.class,null);
        mTabHost.addTab(mTabHost.newTabSpec("發現").setIndicator("發現"),FragmentPage2.class,null);
        mTabHost.addTab(mTabHost.newTabSpec("其他").setIndicator("其他"),FragmentPage2.class,null);
        
        mDetector = new GestureDetector (this);
    }


    @Override 
    public boolean onTouchEvent(MotionEvent event) { 
        return this.mDetector.onTouchEvent(event); 
    } 
    
    @Override
    public boolean onDown(MotionEvent e) {
        // TODO Auto-generated method stub
        return false;
    }
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        // TODO Auto-generated method stub
        int currentTab=this.mTabHost.getCurrentTab();
        if(currentTab<3 && e1.getX()-e2.getX()>120){
            Log.i("MyLog", currentTab+"");
            this.mTabHost.setCurrentTab(currentTab+1);
        }
        else if(currentTab>0 &&  e1.getX()-e2.getX()<-120){
            Log.i("MyLog", currentTab+"");
            this.mTabHost.setCurrentTab(currentTab-1);
        }
        return true;
    }
    @Override
    public void onLongPress(MotionEvent e) {
        // TODO Auto-generated method stub
        
    }
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        // TODO Auto-generated method stub
        return false;
    }
    @Override
    public void onShowPress(MotionEvent e) {
        // TODO Auto-generated method stub
        
    }
    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        // TODO Auto-generated method stub
        return false;
    }
    
}

End.

相關推薦

Android FragmentTabHost+Fragment實現標籤

Android TabHost多標籤頁幾乎是所有APP中必備的控制元件,如通迅錄的【撥號、通話記錄、聯絡人】,微信的【聊天、聯絡人、發現】,如下圖 Android API13之後官方就不推薦使用TabActivity了,取而代之的是FragmentActivity+F

maven profile實現環境打包

作為一名程式設計師,在開發的過程中,經常需要面對不同的執行環境(開發環境、測試環境、生產環境、內網環境、外網環境等等),在不同的環境中,相關的配置一般不一樣,比如資料來源配置、日誌檔案配置、以及一些軟體執行過程中的基本配置。每次在不同環境部署程式時,都需要修改相應的配置檔案,使之完成環境的配置。這麼

Android利用 ACRA 實現在規定時間內崩潰次數超過規定值就自動清理 APP 資料

其實 ACRA 是一個崩潰處理的類庫,其功能就是收集App崩潰堆疊資訊,生成報告併發送到指定端,當然它也可以自己定製對應的操作,所以是個處理崩潰很不錯的庫。 ACRA Application Crash Reports for Android 其實在規定時間內崩潰次數超

Android使用BaseAdapter實現複雜的ListView

步驟 使用BaseAdapter實現複雜的ListView的步驟: 1. 資料你要準備好 List getData()。 2. 繼承ListActivity專有屏,不再需要setContentView(xxx)。  3. 建立一個繼承自Ba

Android用Studio完成裝置解析度的適配

最近研究了一下Android中的自動適配,加上Studio便捷的實時預覽功能,總結一下如何在Android Studio中快速方便適配多種螢幕。 先來補習一下基礎知識,來看幾個名詞解釋: 解析度:整個螢幕的畫素數目,為了表示方便一般用螢幕的畫素寬度(水平畫素數目)乘以畫

Android用RecycleView實現可以橫向滾動的ListView效果

終於閒下來了,總結一下RecycleView的使用。 一、概述 與常見的ListView和GridView一樣,RecycleView也用來在有限的介面上展示大量的資料。它提供了一種插拔式的體驗,高度的解耦,使用非常靈活,可以通過support-v7包進行匯入。先看以下Re

Android動態載入實現的簡單demo

概念▪說明動態載入:此處的動態載入是指從服務端或者其他地方獲取jar包,並在執行時期,載入jar包,並與 jar包互相呼叫。本例中,為了方便演示,將要動態載入的jar放到了assets目錄下,在程式執行時期,將其載入到/data/data/pkgname/files下,來模擬

ViewPager + Fragment實現滑動標籤

ViewPager 結合Fragment實現一個Activity裡包含多個可滑動的標籤頁,每個標籤頁可以有獨立的佈局及響應。 activity_main.xml <?xml version="1.0" encoding="utf-8"?> <Linear

androidandroid實現監聽個按鈕事件

直接擼程式碼: 我有四個按鈕,下面的程式碼演示瞭如何將多個按鈕用一個事件監聽 在onCreate函式裡面 Button button1 = (Button)findViewBy

AndroidAndroid聊天機器人實現

小米 div bottom 曾經 圖靈 .9.png sdn http 歡迎界面 昨天看到一個Android視頻教程講圖靈機器人。那個API接口用起來還是挺方便的,就準備自己動手做一個了。另外自己還使用了高德地圖的API接口用於定位(曾經用過高德的接口,比X度方便) 大

Android實現線程異步小技巧

使用 msg xtend util rri wsh ride 執行 java 方式不止一種,這裏使用的是Timer類,創建一個定時器。我們經常需要獲得移動設備端口的顯示屏信息,但是onCreate()方法執行的時候,OnShow()方法不一定執行了,也就是說,在執行Oncr

Android如何實現Android發送短信

ted param close ase find array 短信 red phone 第一種:調用系統短信接口直接發送短信;主要代碼如下: /** * 直接調用短信接口發短信 * @param phoneNumber * @

Android從無到有:手把手一步步教你使用最簡單的Fragment(三)

轉載請註明出處,原文連結:https://blog.csdn.net/u013642500/article/details/80585416 【本文適用讀者】         用程式碼建立並使用了 Fragment,新增 Fragment 之

Android從無到有:手把手一步步教你使用最簡單的Fragment(二)

轉載請註明出處,原文連結:https://blog.csdn.net/u013642500/article/details/80579389 【本文適用讀者】         targetSdkVersion 版本大於等於 21,即 app 即將有可能

Android從無到有:手把手一步步教你使用最簡單的 Fragment(一)

轉載請註明出處,原文連結:https://blog.csdn.net/u013642500/article/details/80515227 【本文適用讀者】         知道 Fragment 是什麼,不知

Android原始碼分析 - LRUCache快取實現原理

一、Android中的快取策略 一般來說,快取策略主要包含快取的新增、獲取和刪除這三類操作。如何新增和獲取快取這個比較好理解,那麼為什麼還要刪除快取呢?這是因為不管是記憶體快取還是硬碟快取,它們的快取大小都是有限的。當快取滿了之後,再想其新增快取,這個時候就需要刪除一些舊的快取

Android實現XML解析的幾種技術

轉載地址:http://www.cnblogs.com/hanyonglu/archive/2012/02/28/2370675.html  謝謝。 本文介紹在Android平臺中實現對XML的三種解析方式。   XML在各種開發中

Android打電話的兩種實現方式

第一種實現方式:直接給聯絡人打電話 Intent intent=new Intent(); intent.setAction(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:110")); startActivity(intent);

android如何用RedioGroup實現ios中TabBar的效果·

一、xml設定 <RadioGroup android:id="@+id/rg_tab" android:layout_width="fill_parent" android:layo

Android功能設計儲存帳號密碼,自動登入,離線登入實現方案

勾選【記住密碼】【自動登入】複選框時: 什麼也不做,所有操作放在點選【登入】按鈕時執行 點選【登入】按鈕時: 為了簡化程式碼和實現邏輯,不管密碼對錯,登入資訊統一儲存到【上次登入帳號】【上次登入密碼】【是否儲存密碼】【是否自動登入】配置 登入成功