編輯:關於 Android 程式設計
早在 2015 年的 Google I/O 大會上,Google 就帶來了更為完整的 Material Design 設計規範,同時推出了全新的 Android Design Support Library。這個支持庫提供了大量符合 MD 風格的標準控件,而且兼容性極佳,可以直接向下兼容到 Android 2.2。
這段時間要製作一個仿京東的商品詳情頁,頂部的 Tab 切換過去通常得自己寫 ViewPager + Fragment,或者深度定制 Indicator。一直想試試 TabLayout,於是便有了下面的實踐記錄。

先來看看簡單實現的效果(個人覺得坑比較多,某些場景還不如自定義導航器來得靈活):

dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:24.2.0' compile 'com.android.support:design:24.2.0' compile 'com.android.support:recyclerview-v7:24.2.0' compile 'com.android.support:cardview-v7:24.2.0' }
下面是我們要實現的界面布局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/c12" android:gravity="center_vertical" android:minHeight="45dp" android:orientation="horizontal" android:paddingLeft="15dp" android:paddingRight="15dp"> <ImageView android:id="@+id/back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/back_icon" /> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <android.support.design.widget.TabLayout android:id="@+id/tabLayout" android:layout_width="match_parent" android:layout_height="match_parent" app:tabTextAppearance="@style/TabLayoutTextStyle" app:tabGravity="center" app:tabMode="fixed" app:tabTextColor="@color/c7" app:tabSelectedTextColor="@color/c8"/> </LinearLayout> <ImageView android:id="@+id/toolbar_more" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:background="@drawable/more_icon" /> </LinearLayout> <View /> <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <View /> <LinearLayout android:layout_width="match_parent" android:layout_height="48dp" android:background="@color/c12" android:orientation="horizontal"> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"> <TextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="收藏" android:textSize="10sp" /> <View /> <TextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="購物車" android:textSize="10sp" /> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1.5" android:background="@color/c8" android:gravity="center"> <TextView android:gravity="center" android:text="加入購物車" /> </LinearLayout> </LinearLayout> </LinearLayout>
這個布局中最關鍵的一點,是 android.support.design.widget.TabLayout 標簽裡的 app:tabMode 屬性,它決定 Tab 的展示模式。除此之外,TabLayout 的用法和 Indicator 類似,都需要設置適配器,再通過數據完成頁面填充。
public class ProductDetailPagerAdapter extends FragmentPagerAdapter { private List<Fragment> mFragments=null; private List<String> mTitles=null; public ProductDetailPagerAdapter(FragmentManager fm, List<Fragment> mFragments,List<String> mTitles) { super(fm); this.mFragments =mFragments; this.mTitles=mTitles; } public ProductDetailPagerAdapter(FragmentManager fm, Fragment... fragments) { super(fm); this.mFragments = Arrays.asList(fragments); } @Override public Fragment getItem(int position) { return mFragments.get(position); } @Override public int getCount() { return mFragments.size(); } @Override public CharSequence getPageTitle(int position) { return mTitles.get(position); } }
這裡的 Fragment 都是最簡單的實現,重點在於把 ViewPager 和 TabLayout 關聯起來:
public class ProductDetailsActivity extends BaseActivity { @BindView(R.id.viewPager) ViewPager viewPager; @BindView(R.id.toolbar_more) ImageView toolbarMore; @BindView(R.id.tabLayout) TabLayout tabLayout; private List<Fragment> mFragments; private String[] titles = new String[]{"商品", "詳情"}; private ProductDetailPagerAdapter productPagerAdapter = null; private MorePopupWindow popupWindow = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_product_details); ButterKnife.bind(this); init(); } private void init() { initViewPager(); } private void initViewPager() { mFragments = new ArrayList<>(); mFragments.add(new ProductFragment()); mFragments.add(new ProductDetailFragment()); productPagerAdapter = new ProductDetailPagerAdapter(getSupportFragmentManager(), mFragments, Arrays.asList(titles)); viewPager.setOffscreenPageLimit(2); viewPager.setAdapter(productPagerAdapter); viewPager.setCurrentItem(1); tabLayout.setupWithViewPager(viewPager); } @OnClick(R.id.back) public void backClick() { finish(); } @OnClick(R.id.toolbar_more) public void moreClick() { } private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { popupWindow.dismiss(); } }; public static void open(Context context) { Intent intent = new Intent(context, ProductDetailsActivity.class); context.startActivity(intent); } }
使用 TabLayout 時有一點要特別注意,tabMode 有兩個可選值:
MODE_FIXED:所有 Tab 同時並排顯示,適合需要在少數 Tab 之間快速切換的場景。
MODE_SCROLLABLE:任一時刻只顯示部分 Tab,可以容納更長的標籤文字和更多的 Tab 數量。
簡單來說,MODE_SCROLLABLE 適合 Tab 較多的情況,可以橫向滾動;而想實現京東那種所有 Tab 擠在一起的顯示效果,就需要用 MODE_FIXED。
為了更好地滿足定制需求,TabLayout 還支持通過引入 app:tabTextAppearance="" 來自定義樣式。
TabLayout 本身沒有直接添加 icon 的方法,我們可以借助 SpannableString 結合 ImageSpan 來實現:
private int[] imageResId = { R.drawable.ic_one, R.drawable.ic_two, R.drawable.ic_three }; // ... @Override public CharSequence getPageTitle(int position) { // Generate title based on item position // return tabTitles[position]; Drawable image = context.getResources().getDrawable(imageResId[position]); image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight()); SpannableString sb = new SpannableString(" "); ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM); sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return sb; }
運行後會發現圖標並沒有顯示,原因是 TabLayout 創建的 Tab 默認把 textAllCaps 屬性設為 true,這會阻止 ImageSpan 被渲染。可以通過下面的樣式文件來修正:
<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout"> <item name="tabTextAppearance">@style/MyCustomTextAppearance</item> </style> <style name="MyCustomTextAppearance" parent="TextAppearance.Design.Tab"> <item name="textAllCaps">false</item> </style>
然後在 getPageTitle 方法中,讓 Tab 同時顯示圖標和文字:
@Override public CharSequence getPageTitle(int position) { // Generate title based on item position Drawable image = context.getResources().getDrawable(imageResId[position]); image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight()); // Replace blank spaces with image icon SpannableString sb = new SpannableString(" " + tabTitles[position]); ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM); sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return sb; }
此外,TabLayout 還支持通過 getTabView 設置自定義 View,這裡就不展開了,感興趣的同學可以自行深入研究。

部分源碼地址:https://github.com/xiangzhihong/jingdongApp
以上就是本文的全部內容,希望對大家的學習有所幫助。
Android 透過 JSON 將資料寫入 MySQL 的完整實作(寫入篇)
上一篇講了讀取,這篇來談寫入。Android 把本地資料(例如定位、感測器讀數)上傳到資料庫,流程是:把參數封裝成 POST 表單 → 送到 PHP → PHP 寫入 M
Android 學習路線(二十二):用 Fragment 打造動態 UI —— 打造靈活的版面
先把位置佔著,翻譯待補。以下暫留原文,日後再整理成中文。 When designing your application to support a wide range
Android 教學:透過 JNI 靜態(static)方式載入 OpenCV
透過 JNI 靜態(static)方式載入 OpenCV原文出處:https://blog.csdn.net/caroline_wendy整體步驟如下: 1. 準備 Op
【屬性動畫 Property Animator】從原理到實戰
1、為什麼要使用屬性動畫? Google 在 3.0 之後推出了屬性動畫。之所以會誕生屬性動畫,是因為傳統動畫在物件交互上存在缺陷。透過一個經典的例子,就能看出兩者的區別