版權聲明:本文為HaiyuKing原創文章,轉載請注明出處!
前言
使用TabLayout實現底部選項卡切換功能。
效果圖
代碼分析
1、演示固定模式的展現
2、演示自定義布局的實現
使用步驟
一、項目組織結構圖
注意事項:
1、 導入類文件后需要change包名以及重新import R文件路徑
2、 Values目錄下的文件(strings.xml、dimens.xml、colors.xml等),如果項目中存在,則復制里面的內容,不要整個覆蓋
二、導入步驟
引入依賴庫
在APP的build.gradle文件中添加以下代碼【注意:版本號和com.android.support:appcompat-v7保持一致】
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.why.project.tablayoutbottomdemo"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
testCompile 'junit:junit:4.12'
//TabLayout compile 'com.android.support:design:25.3.1'
}
將選項卡子項布局文件tab_bottom_item.xml文件復制到項目中

<?xml version="1.0" encoding="utf-8"?> <!-- 底部選項卡區域的子選項卡布局文件 --> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/tab_bg_normal" android:gravity="center" > <!-- android:checkMark="?android:attr/listChoiceIndicatorMultiple"代表多選 android:checkMark="?android:attr/listChoiceIndicatorSingle" 代表單選 該屬性不添加的話,不會顯示方框或者圓點 --> <!-- android:drawableTop的屬性值使用drawable目錄下的selector選擇器 --> <!-- android:tag="tag1"用於checkedTextview的索引 --> <!-- 選項卡的內容(圖片+文字)類似RadioButton --> <!--android:textAlignment="center" 文本居中--> <CheckedTextView android:id="@+id/bottomtab_checkedTextView" android:tag="tag1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="" android:textSize="@dimen/tab_text_size" android:textColor="@color/tab_text_normal" android:textAlignment="center" /> </RelativeLayout>
將圖片資源和selector文件復制到項目中【后續可根據實際情況更換圖片】
在colors.xml文件中添加以下代碼:【后續可根據實際情況更改背景顏色、文字顏色值】
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> <!-- *********************************底部選項卡區域********************************* --> <!-- 底部選項卡底部背景色 --> <color name="tab_bg_normal">#00000000</color> <color name="tab_bg_selected">#00000000</color> <!-- 底部選項卡文本顏色 --> <color name="tab_text_normal">#8a8a8a</color> <color name="tab_text_selected">#38ADFF</color> </resources>
在dimens.xml文件中添加以下代碼:【后續可根據實際情況更改底部選項卡區域的高度值、文字大小值】
<resources> <!-- Default screen margins, per the Android Design guidelines. --> <dimen name="activity_horizontal_margin">16dp</dimen> <dimen name="activity_vertical_margin">16dp</dimen> <!-- *********************************底部選項卡區域********************************* --> <!--底部選項卡高度值--> <dimen name="tab_bottom_background_height">56dp</dimen> <!-- 底部選項卡文本大小 --> <dimen name="tab_text_size">14sp</dimen> <dimen name="tab_medium_text_size">16sp</dimen> <dimen name="tab_larger_text_size">18sp</dimen> <dimen name="tab_larger_small_text_size">20sp</dimen> </resources>
在strings.xml文件中添加以下代碼:【后續可根據實際情況更改底部選項卡的文字內容】
<resources> <string name="app_name">TabLayoutBottomDemo</string> <!-- *********************************底部選項卡區域********************************* --> <string name="home_function_home">首頁</string> <string name="home_function_message">消息</string> <string name="home_function_contact">我的</string> </resources>
至此,選項卡子項的布局所需的文件已集成到項目中了。
三、使用方法
在Activity布局文件中引用TabLayout
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.why.project.tablayoutbottomdemo.MainActivity"> <!-- viewpager區域 --> <android.support.v4.view.ViewPager android:id="@+id/vp_tab" android:layout_width="match_parent" android:layout_height="0.0dp" android:layout_weight="1"/> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#cfcfcf"> </View> <!-- 選項卡區域 --> <!--設置TabLayout的模式 app:tabMode 默認是fixed:固定的,標簽很多時候會被擠壓,不能滑動。--> <!--設置整個TabLayout的顏色 app:tabBackground--> <!--設置選中字體的顏色 app:tabSelectedTextColor--> <!--設置未選中字體的顏色 app:tabTextColor--> <!--設置指示器下標的顏色 app:tabIndicatorColor--> <!--設置指示器下標的高度 app:tabIndicatorHeight,如果設置的是0.0dp,則代表沒有下划線--> <!--設置內容的顯示模式 app:tabGravity,center : 居中,如果是fill,則是充滿--> <android.support.design.widget.TabLayout android:id="@+id/tl_top" android:layout_width="match_parent" android:layout_height="@dimen/tab_bottom_background_height" app:tabBackground="@android:color/transparent" app:tabMode="fixed" app:tabIndicatorHeight="0dp" app:tabGravity="fill" /> </LinearLayout>
創建需要用到的fragment類和布局文件【后續可根據實際情況更改命名,並且需要重新import R文件】
創建選項卡子項model類TabItemModel
package com.why.project.tablayoutbottomdemo.model; /** * Created by HaiyuKing * Used */ public class TabItemModel { private String tabTitle; private int tabImgResd; public TabItemModel(String tabTitle, int tabImgResd){ this.tabTitle = tabTitle; this.tabImgResd = tabImgResd; } public String getTabTitle() { return tabTitle; } public void setTabTitle(String tabTitle) { this.tabTitle = tabTitle; } public int getTabImgResd() { return tabImgResd; } public void setTabImgResd(int tabImgResd) { this.tabImgResd = tabImgResd; } }
創建viewpager的適配器
package com.why.project.tablayoutbottomdemo.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.why.project.tablayoutbottomdemo.model.TabItemModel; import java.util.List; /** * Created by HaiyuKing * Used */ public class ContentPagerAdapter extends FragmentPagerAdapter { private List<TabItemModel> tabIndicators; private List<Fragment> tabItemList; public ContentPagerAdapter(FragmentManager fm, List<TabItemModel> tabIndicators, List<Fragment> tabItemList) { super(fm); this.tabIndicators = tabIndicators; this.tabItemList = tabItemList; } @Override public Fragment getItem(int position) { return tabItemList.get(position); } @Override public int getCount() { return tabItemList.size(); } @Override public CharSequence getPageTitle(int position) { return tabIndicators.get(position).getTabTitle(); } }
在Activity中使用如下【繼承FragmentActivity或者其子類】
package com.why.project.tablayoutbottomdemo; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.CheckedTextView; import com.why.project.tablayoutbottomdemo.adapter.ContentPagerAdapter; import com.why.project.tablayoutbottomdemo.fragment.ContactFragment; import com.why.project.tablayoutbottomdemo.fragment.HomeFragment; import com.why.project.tablayoutbottomdemo.fragment.MessageFragment; import com.why.project.tablayoutbottomdemo.model.TabItemModel; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private TabLayout mTabLayout; private ViewPager mTabViewPager; /**碎片聲明*/ private HomeFragment homeFragment;//首頁 private MessageFragment messageFragment;//消息 private ContactFragment contactFragment;//我的 private List<TabItemModel> tabIndicators; private List<Fragment> tabFragments; private ContentPagerAdapter contentAdapter; //選項卡的各個選項的CheckedTextView的集合:用於切換時改變圖標和文字顏色 private List<CheckedTextView> bottomTab_checkeds = new ArrayList<CheckedTextView>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); initDatas(); initEvents(); } private void initViews() { mTabLayout = (TabLayout) findViewById(R.id.tl_top); mTabViewPager = (ViewPager) findViewById(R.id.vp_tab); } private void initDatas() { //初始化選項卡子項的文本、圖標model集合 tabIndicators = new ArrayList<TabItemModel>(); tabIndicators.add(new TabItemModel(getResources().getString(R.string.home_function_home), R.drawable.home_tab_home_selector)); tabIndicators.add(new TabItemModel(getResources().getString(R.string.home_function_message), R.drawable.home_tab_message_selector)); tabIndicators.add(new TabItemModel(getResources().getString(R.string.home_function_contact), R.drawable.home_tab_contact_selector)); //初始化碎片集合 tabFragments = new ArrayList<>(); homeFragment = HomeFragment.getInstance(HomeFragment.class,null); messageFragment = MessageFragment.getInstance(MessageFragment.class,null); contactFragment = ContactFragment.getInstance(ContactFragment.class,null); tabFragments.add(homeFragment); tabFragments.add(messageFragment); tabFragments.add(contactFragment); //實例化Adapter contentAdapter = new ContentPagerAdapter(getSupportFragmentManager(),tabIndicators,tabFragments); mTabViewPager.setAdapter(contentAdapter); //TabLayout和ViewPager相關聯 mTabLayout.setupWithViewPager(mTabViewPager); //自定義布局的話,必須放到setupWithViewPager后面 for (int i = 0; i < tabIndicators.size(); i++) { TabLayout.Tab itemTab = mTabLayout.getTabAt(i); if (itemTab!=null){ itemTab.setCustomView(R.layout.tab_bottom_item); View bottomtabitemView = itemTab.getCustomView(); //===========設置CheckedTextView控件的圖片和文字========== final CheckedTextView bottomtab_checkedTextView = (CheckedTextView) bottomtabitemView.findViewById(R.id.bottomtab_checkedTextView); //設置CheckedTextView控件的android:drawableTop屬性值 Drawable drawable = ContextCompat.getDrawable(this,tabIndicators.get(i).getTabImgResd()); //setCompoundDrawables 畫的drawable的寬高是按drawable.setBound()設置的寬高 //而setCompoundDrawablesWithIntrinsicBounds是畫的drawable的寬高是按drawable固定的寬高,即通過getIntrinsicWidth()與getIntrinsicHeight()自動獲得 drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); bottomtab_checkedTextView.setCompoundDrawables(null, drawable, null, null); //bottomtab_checkedTextView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null); //設置CheckedTextView的文字 bottomtab_checkedTextView.setText(tabIndicators.get(i).getTabTitle()); bottomTab_checkeds.add(bottomtab_checkedTextView); } } //設置第一選項卡為選中狀態 mTabLayout.getTabAt(0).getCustomView().setSelected(true); bottomTab_checkeds.get(0).setTextColor(getResources().getColor(R.color.tab_text_selected)); } private void initEvents() { mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { //選中了tab的邏輯 bottomTab_checkeds.get(tab.getPosition()).setTextColor(getResources().getColor(R.color.tab_text_selected)); } @Override public void onTabUnselected(TabLayout.Tab tab) { //未選中了tab的邏輯 bottomTab_checkeds.get(tab.getPosition()).setTextColor(getResources().getColor(R.color.tab_text_normal)); } @Override public void onTabReselected(TabLayout.Tab tab) { //再次選中了tab的邏輯 } }); } }
混淆配置
無
參考資料
Android TabLayout 分分鍾打造一個滑動標簽頁