編輯:關於 Android 程式設計

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

更新完成後,在 build.gradle 中加入:
compile 'com.android.support:design:22.2.0'
顧名思義,這是一個浮動在畫面上的按鈕。

上圖是三種不同設定的效果。由於 FloatingActionButton 是繼承自 ImageView,所以它擁有 ImageView 的所有屬性,這一點在後面會造成一個小陷阱。
控制外觀的關鍵屬性有三個:
<item name="colorAccent">#ff0000</item>
注意:不能用 android:background 改背景色,只能用 app:backgroundTint。原因就是前面提到的——它繼承自 ImageView,背景由庫自己管控。
這個元件用來包裝 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 定位在 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 實現的是常見的頂部選項卡效果。過去這個需求通常要找 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():建立一個 TabgetTabAt(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 這幾個元件,會在下一篇中介紹。以上程式碼若有疑問,歡迎一起討論。
Android ViewGroup 觸摸事件攔截完全解析
前言在自定義 ViewGroup 的開發過程中,觸摸事件的攔截幾乎是繞不開的一環。最典型的例子莫過於 ListView 的下拉刷新——手指下滑時,列表並不把事件交給子項,
Android UI 入門:視圖體系與常用控制項全梳理
一、UI 是什麼 對 App 來說,使用者介面幾乎就是全部——使用者看得見、點得到的一切都屬於 UI。Android 的 UI 大致可以分成系統提供的元件與自定義元件兩類
選擇 Visual Studio 開發 Android 的十大理由
Visual Studio:C++ 跨平台的行動方案 Visual Studio 正在快速成為一個跨平台的 C++ IDE。目標很明確:讓它成為你撰寫 C++ 跨平台程式
用 WindowManager 在應用最上層繪製懸浮 View
一般來說,Android 顯示一個 View 都是透過 Activity 的 setContentView 來設定。但其實還有一條路:直接用 WindowManager