Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Material Design 新元件實戰:FloatingActionButton、TextInputLayout、Snackbar 與 TabLayout

編輯:關於 Android 程式設計

在 2015 年的 Google I/O 大會上,Android 新版本 M 正式亮相——從這版開始,Android 不再以數字命名版本。這次更新幅度不算大,主要是把 Android L 的 Design 語言補齊完善,並推出了 Design Support Library,讓開發者不必依賴第三方開源庫,就能直接使用官方版的 Material Design 元件。

前提:更新 SDK 與引入 Design 庫

要使用這些元件,必須先更新 SDK Extras 中的 Support Library:

更新完成後,在 build.gradle 中加入:

compile 'com.android.support:design:22.2.0'

FloatingActionButton

顧名思義,這是一個浮動在畫面上的按鈕。

上圖是三種不同設定的效果。由於 FloatingActionButton 是繼承自 ImageView,所以它擁有 ImageView 的所有屬性,這一點在後面會造成一個小陷阱。

控制外觀的關鍵屬性有三個:

  • app:fabSize:尺寸,可選 "mini" 或 "normal",預設 normal。
  • app:backgroundTint:背景色,預設取主題中的 colorAccent:
<item name="colorAccent">#ff0000</item>
  • app:elevation:陰影深度,預設有陰影,覺得太重可以調小。

注意:不能用 android:background 改背景色,只能用 app:backgroundTint。原因就是前面提到的——它繼承自 ImageView,背景由庫自己管控。

TextInputLayout

這個元件用來包裝 EditText,解決一個很實際的痛點:以往 EditText 取得焦點後,hint 提示文字會消失。當一個頁面有多個輸入框時,使用者很容易忘記目前這個欄位要填什麼。

TextInputLayout 繼承自 LinearLayout,是個容器,所以必須把 EditText 放在裡面才能生效,不能單獨使用:

<TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black" />
</TextInputLayout>

除了讓提示文字上彈到輸入框上方,它還能在下方顯示錯誤訊息,這在表單驗證時非常好用:

final TextInputLayout inputLayout = (TextInputLayout) findViewById(R.id.textInput);
inputLayout.setHint("請輸入姓名:");
EditText editText = inputLayout.getEditText();
editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() > 4) {
            inputLayout.setErrorEnabled(true);
            inputLayout.setError("姓名長度不能超過4個");
        } else {
            inputLayout.setErrorEnabled(false);
        }
    }

    @Override
    public void afterTextChanged(Editable s) { }
});

常用方法:setHint() 設定提示語、getEditText() 取得內部 EditText、setErrorEnabled() 決定是否顯示錯誤區、setError() 設定錯誤內容。

Snackbar

Snackbar 定位在 Toast 與 AlertDialog 之間,是一個輕量級的提示元件,除了顯示訊息,還能附帶一個操作按鈕。

用法與 Toast 類似:

final Snackbar snackbar = Snackbar.make(inputLayout, "測試彈出提示", Snackbar.LENGTH_LONG);
snackbar.show();
snackbar.setAction("取消", new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        snackbar.dismiss();
    }
});

第一個參數可以是父布局中的任何 View。Action 的方法簽名是 setAction(CharSequence text, View.OnClickListener listener),Action 文字預設使用主題的 colorAccent,也可以用 setActionTextColor(int color) 自訂。

兩點提醒:Snackbar 可以設定多個 Action 行為事件;它是從整個畫面的底部彈出,因此放置的 View 會影響顯示位置。

TabLayout

TabLayout 實現的是常見的頂部選項卡效果。過去這個需求通常要找 GitHub 上的開源庫,現在官方把它內建了。

最關鍵的三個屬性:

app:tabSelectedTextColor="@android:color/holo_blue_bright"
app:tabTextColor="@android:color/black"
app:tabIndicatorColor="@android:color/holo_blue_bright"

分別對應選中時字色、未選中字色,以及下方指示條的顏色。

常用方法:

  • addTab(tab, position, setSelected) / addTab(tab, setSelected) / addTab(tab):加入選項卡
  • newTab():建立一個 Tab
  • getTabAt(index)、getTabCount()、getTabGravity()、getTabMode()、getTabTextColors():取得各項狀態
  • removeTab(tab)、removeTabAt(position)、removeAllTabs():移除
  • setOnTabSelectedListener(...):設定選擇監聽器
  • setTabGravity(int)、setTabMode(int)、setTabTextColors(...)、setScrollPosition(...):外觀與位置設定
  • setTabsFromPagerAdapter(adapter)、setupWithViewPager(viewPager):與 ViewPager 聯動

實際上 TabLayout 幾乎都是與 ViewPager 搭配使用:

viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);

List<String> tabList = new ArrayList<>();
tabList.add("Tab1");
tabList.add("Tab2");
tabList.add("Tab3");

tabLayout.setTabMode(TabLayout.MODE_FIXED); // 目前為系統預設模式
tabLayout.addTab(tabLayout.newTab().setText(tabList.get(0)));
tabLayout.addTab(tabLayout.newTab().setText(tabList.get(1)));
tabLayout.addTab(tabLayout.newTab().setText(tabList.get(2)));

List<Fragment> fragmentList = new ArrayList<>();
for (int i = 0; i < tabList.size(); i++) {
    Fragment f1 = new TabFragment();
    Bundle bundle = new Bundle();
    bundle.putString("content", "內容 " + i);
    f1.setArguments(bundle);
    fragmentList.add(f1);
}

TabFragmentAdapter fragmentAdapter =
        new TabFragmentAdapter(getSupportFragmentManager(), fragmentList, tabList);
viewPager.setAdapter(fragmentAdapter);
tabLayout.setupWithViewPager(viewPager);      // 兩者關聯
tabLayout.setTabsFromPagerAdapter(fragmentAdapter);

配套的 Adapter:

public class TabFragmentAdapter extends FragmentStatePagerAdapter {
    private List<Fragment> mFragments;
    private List<String> mTitles;

    public TabFragmentAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titles) {
        super(fm);
        mFragments = fragments;
        mTitles = titles;
    }

    @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:

public class TabFragment extends Fragment {
    private String content;
    private View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.item, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        content = getArguments().getString("content");
        TextView tvContent = (TextView) view.findViewById(R.id.tv_tab_content);
        tvContent.setText(content + "");
    }
}

常見疑問:當 tab 數量多到超過螢幕寬度時,為什麼不能水平滑動?其實 TabLayout 是支援的,只要指定可滾動模式:

tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

MODE_FIXED 與 MODE_SCROLLABLE 的差別就在這裡,預設是前者。

接下來

CoordinatorLayout、CollapsingToolbarLayout、AppBarLayout 與 NavigationView 這幾個元件,會在下一篇中介紹。以上程式碼若有疑問,歡迎一起討論。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved