對於移動應用來說,導航欄是非常重要的一個組件。合適的導航欄可以幫助用戶快速準確地找到自己所需的功能,從而提高用戶體驗。而TabLayout和ViewPager的結合使用可以大大提升移動應用導航欄的用戶體驗。
一、 TabLayout和ViewPager的基本使用
首先,我們需要知道TabLayout和ViewPager是什麼。TabLayout是Google在Design Support庫中提供的一種新的導航欄控件,它可以方便地實現標籤頁布局。ViewPager是一個可滑動的容器視圖,通常它用來存放Fragment,使得應用可以在不同的Fragment之間進行切換。
在使用TabLayout和ViewPager之前,首先需要在項目的build.gradle文件中添加以下依賴:
<dependency>
<groupId>com.android.support</groupId>
<artifactId>design</artifactId>
<version>23.1.1</version>
</dependency>
接下來,我們需要創建一個布局文件,以添加TabLayout和ViewPager:
<?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">
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:tabMode="scrollable"
android:tabTextColor="@android:color/white"
android:textColorSecondary="@android:color/white"
android:scrollbars="none" />
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
在這個布局中,我們首先添加了一個TabLayout控件,並且在其中定義了一些屬性。其中,tabMode用於設置標籤的模式,可以是fixed(固定標籤寬度)或者scrollable(可滑動);tabTextColor用於設置標籤字體的顏色;textColorSecondary用於設置選中標籤的顏色;scrollbars用於設置標籤中的捲軸是否顯示。
接下來,我們添加了一個ViewPager控件,用於存放Fragment。我們在這個ViewPager中添加了一個FragmentPagerAdapter對象,並在其中實現了getItem()和getCount()方法,用於獲取每個Fragment和Fragment的總數。
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[] { "Tab1", "Tab2", "Tab3" };
public SampleFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return PAGE_COUNT;
}
@Override
public Fragment getItem(int position) {
return PageFragment.newInstance(position + 1);
}
@Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
在這個FragmentPagerAdapter中,我們創建了三個Fragment,每一個Fragment都可以使用PageFragment.newInstance()方法來創建,這裡我們傳入了一個代表頁面位置的參數。
最後,在我們的Activity中,我們需要做以下幾個操作:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 設置ViewPager
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager()));
// 設置TabLayout
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
}
在這個Activity中,我們先獲取了ViewPager和TabLayout的實例,並且在ViewPager中設置了我們剛才創建的FragmentPagerAdapter。接着,我們調用了TabLayout的setupWithViewPager()方法,使得TabLayout和ViewPager進行了綁定。
二、 使用自定義布局和樣式
雖然TabLayout已經提供了默認的布局樣式,但是我們也可以使用自定義的布局和樣式。下面是一個簡單的自定義TabLayout布局樣式的例子:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.TabLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab_layout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:tabIndicatorColor="@android:color/white"
android:tabSelectedTextColor="@android:color/white"
android:tabTextColor="@color/tab_text_color"
app:tabIndicatorHeight="4dp"
app:tabMode="scrollable"
app:tabPaddingEnd="16dp"
app:tabPaddingStart="16dp"
app:tabTextAppearance="@style/MyTabLayoutTextAppearance"
app:tabSelectedBackground="@drawable/tab_selector"
app:tabBackground="@drawable/tab_selector" />
在這個布局樣式中,我們定義了一些新的屬性,例如tabIndicatorColor用於設置標籤指示器的顏色,tabSelectedTextColor用於設置選中標籤字體的顏色。我們還可以在TabLayout裡面設置tabPaddingEnd、tabPaddingStart等屬性,用於設置標籤的邊距。如果我們想在標籤中添加圖片或者自定義樣式,我們可以通過app:tabTextAppearance屬性來實現。例如下面這個定義了自定義樣式的TabLayout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.TabLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab_layout3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
app:tabIndicatorColor="@android:color/white"
app:tabSelectedTextColor="@android:color/white"
app:tabTextColor="@color/tab_text_color"
app:tabIndicatorHeight="4dp"
app:tabMode="scrollable"
app:tabPaddingEnd="16dp"
app:tabPaddingStart="16dp"
app:tabTextAppearance="@style/MyTabLayoutTextAppearance"
app:tabSelectedBackground="@drawable/tab_selector"
app:tabBackground="@drawable/tab_selector" />
在這個自定義樣式布局中,我們定義了一個樣式文件——MyTabLayoutTextAppearance,用於定義標籤的樣式。
<style name="MyTabLayoutTextAppearance" parent="TextAppearance.Design.Tab">
<item name="android:textSize">14sp</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">?attr/colorPrimary</item>
</style>
在這個樣式文件中,我們定義了標籤字體的大小(textSize)、粗細(textStyle)和顏色(textColor)。
三、 TabLayout和ViewPager的進階用法
除了基本的使用方法外,TabLayout和ViewPager還有一些很有用的進階用法,例如TabLayout中添加圖標、重複點擊標籤的處理和聯動標題欄等。下面我們來看一下這些用法具體是怎麼實現的。
1. TabLayout中添加圖標
我們可以在TabLayout中添加圖標,可以讓我們的導航欄變得更加美觀。使用方法也很簡單,只需要在創建FragmentPagerAdapter的時候,重寫getPageIcon()方法即可。下面是實現代碼:
@Override
public Fragment getItem(int position) {
return PageFragment.newInstance(position + 1);
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Drawable drawable = null;
switch (position) {
case 0:
drawable = getResources().getDrawable(R.drawable.tab_home_selector);
break;
case 1:
drawable = getResources().getDrawable(R.drawable.tab_discovery_selector);
break;
case 2:
drawable = getResources().getDrawable(R.drawable.tab_me_selector);
break;
default:
break;
}
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
SpannableString spannableString = new SpannableString(" " + tabTitles[position]);
ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
spannableString.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
public Drawable getDrawable(int position) {
Drawable drawable = null;
switch (position) {
case 0:
drawable = getResources().getDrawable(R.drawable.tab_home_selector);
break;
case 1:
drawable = getResources().getDrawable(R.drawable.tab_discovery_selector);
break;
case 2:
drawable = getResources().getDrawable(R.drawable.tab_me_selector);
break;
default:
break;
}
return drawable;
}
在這個例子中,我們在getPageTitle()方法中獲取了每個標籤頁所對應的圖片,並通過ImageSpan將圖片和文字整合在了一起。
2. 重複點擊標籤的處理
在默認情況下,如果我們重複點擊同一個標籤,ViewPager是不會響應的。但是在某些情況下,我們需要重複點擊同一個標籤時也能夠響應,這時候我們可以使用addOnTabSelectedListener()和setOnTouchListener()方法來實現。下面是實現代碼:
tabLayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
if (tabLayout.getSelectedTabPosition() == tab.getPosition()) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.view_pager + ":" + viewPager.getCurrentItem());
if (fragment != null && fragment instanceof PageFragment) {
((PageFragment) fragment).scrollToTop();
}
}
}
});
for (int i = 0; i < tabLayout.getTabCount(); i++) {
View tab = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
tab.setTag(i);
tab.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mLastPos = (Integer) v.getTag();
} else if (event.getAction() == MotionEvent.ACTION_UP
&& mLastPos == (Integer) v.getTag()
&& tabLayout.getSelectedTabPosition() == (Integer) v.getTag()) {
onDoubleClick((Integer) v.getTag());
}
return false;
}
});
}
private void onDoubleClick(int position) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.view_pager + ":" + viewPager.getCurrentItem());
if (fragment != null && fragment instanceof PageFragment) {
((PageFragment) fragment).scrollToTop();
}
}
在這個代碼片段中,我們首先使用addOnTabSelectedListener()方法來監聽選中的標籤,並在onTabReselected()方法裡面判斷是否為第一次點擊標籤。如果是第一次點擊標籤,我們就不做任何處理,否則我們可以在這個方法裡面處理重複點擊標籤的事件。
接着,我們使用了setOnTouchListener()方法來監聽標籤的點擊事件。在這個方法中,我們首先獲取了當前點擊的標籤位置,並且判斷是否為重複點擊。如果是重複點擊,就會調用onDoubleClick()方法,處理我們需要處理的事件。
3. 聯動標題欄</h3原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/307287.html
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/307287.html