天天看點

Android M新控件之FloatingActionButton,TextInputLayout,Snackbar,TabLayout的使用

【轉載請注明出處:http://blog.csdn.net/feiduclear_up/article/details/46500865 CSDN 廢墟的樹】

Android M新控件之FloatingActionButton,TextInputLayout,Snackbar,TabLayout的使用

在前不久的谷歌2015 I/O大會上,釋出了Android新版本M,貌似從這個版本開始Android不在以數字命名版本了。

在這次的I/O大會上谷歌對Android并沒有很大的改變,主要是修改完善之前Android L版本。不過在谷歌推出

Material Design設計風格之後,還是做了很多風格上的相容,比如v7包的 RecyclerView,CardView,Palette等

這次的I/O大會上也繼續完善了MD設計支援庫,這次谷歌推出了Android Design Support Library 庫,全面支援

MD設計風格的UI效果。Design Support Library庫吸收了8 個新的 material design 元件!最低支援 Android

2.1,其實很多元件都是Github上比較火的,隻是谷歌把它官方化了,便于開發者使用。今天我們來學習

FloatingActionButton,TextInputLayout,Snackbar,TabLayout 四種控件。

前提

為了能使用 這些 material design 元件,你需要去更新最新的SDK中的Extras支援庫,如下圖:

Android M新控件之FloatingActionButton,TextInputLayout,Snackbar,TabLayout的使用

ps:在天朝上國,這種更新是需要翻牆的或者使用代理的,大家自行想辦法。

更新完之後,在build.gralde檔案下引入如下包:

現在,我們可以開始使用Material Design元件啦!來看看新元件有什麼特别的地方吧!

FloatingActionButton

顧名思義:這是一個浮動按鈕。先上效果圖啦!ps:沒有效果圖的UI部落格很蛋疼的。

Android M新控件之FloatingActionButton,TextInputLayout,Snackbar,TabLayout的使用

以上是三種不同效果的FloatingActionButton。XML布局代碼如下:

<android.support.design.widget.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_discuss"
             />
           

由于FloatingActionButton是重寫ImageView的,所有FloatingActionButton擁有ImageView的一切屬性。為了

控制FloatingActionButton的大小,背景顔色,陰影的深度等,我們可以通過如下屬性來控制這些效果:

  1. app:fabSize :FloatingActionButton的大小,有兩種指派分别是 “mini” 和 “normal”,預設是“normal”.
  2. app:backgroundTint:FloatingActionButton的背景顔色,預設的背景顔色是Theme主題中的

顔色,不了解的童鞋們可以參考Android5.x新特性之 Toolbar和Theme的使用:http://blog.csdn.net/feiduclear_up/article/details/46457433。

3. app:elevation :FloatingActionButton陰影的深度,預設是有陰影的,如果覺得預設陰影深度有點大,可以改變這個屬性來修改陰影深度。

上面三個效果圖的XML布局代碼如下:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_discuss"
            app:fabSize="mini" />

        <android.support.design.widget.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_discuss"
             />

        <android.support.design.widget.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_discuss"
            app:backgroundTint="#000af4"
            app:fabSize="normal"
            app:elevation="1dp"
             />

    </LinearLayout>
           

注意點

  1. 不能通過 android:background 屬性來改變 FloatingActionButton的背景顔色,隻能通過app:backgroundTint屬性改變,因為FloatingActionButton是繼承自ImageView的。

TextInputLayout

該控件是用于EditView輸入框的,主要解決之前EditView在獲得焦點編輯時hint屬性提示語消失,這一點在一個頁

面有多個EditView輸入框的時候不是很好,因為很有可能使用者在輸入多個EditView之後,不知道目前EditView需

要輸入什麼内容。為了解決這一問題,TextInputLayout就此誕生了。TextInputLayout是繼承自LinearLayout容

器布局,是以我們需要将EditView包含在TextInputLayout之内才可以使用,言外之意:TextInputLayout不能單

獨使用。廢話不多說,先上效果圖啊:

Android M新控件之FloatingActionButton,TextInputLayout,Snackbar,TabLayout的使用

XML布局代碼如下:

<android.support.design.widget.TextInputLayout
        android:id="@+id/textInput"
        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"/>
    </android.support.design.widget.TextInputLayout>
           

代碼也可以看出TextInputLayout包裹着EditView。

為了達到以上效果,我們還需添加如下代碼:

final TextInputLayout  inputLayout = findView(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()>){
                    inputLayout.setErrorEnabled(true);
                    inputLayout.setError("姓名長度不能超過4個");
                }else{
                    inputLayout.setErrorEnabled(false);
                }
            }

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

TextInputLayout 不僅能讓EditView的提示語上彈顯示在EditView之上,而且還能把錯誤資訊顯示在EditView之下。

TextInputLayout常用的方法有如下:

  1. setHint():設定提示語。
  2. getEditText():得到TextInputLayout中的EditView控件。
  3. setErrorEnabled():設定是否可以顯示錯誤資訊。
  4. setError():設定當使用者輸入錯誤時彈出的錯誤資訊。

注意點

  1. TextInputLayout不能單獨使用,需要包裹EditView元件。

【轉載請注明出處:http://blog.csdn.net/feiduclear_up/article/details/46500865 CSDN 廢墟的樹】

Snackbar的使用

Snackbar提供了一個介于Toast和AlertDialog之間輕量級控件,它可以很友善的提供消息的提示和動作回報。

廢話不少說,妹子,上圖:

Android M新控件之FloatingActionButton,TextInputLayout,Snackbar,TabLayout的使用

Snackbar的使用和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 可以是目前父布局中的任何一個view對象都可以。之後的參數和Toast參數一樣。Snackbar可以

設定Action行為事件,使用的方法是public Snackbar setAction (CharSequence text, View.OnClickListener listener); Action的字型顔色預設使用系統主題中的如下顔色

當然你可以通過代碼去改變Action的字型顔色:Snackbar setActionTextColor (int color);

注意

  1. Snackbar是從整個界面的底部彈出。

TabLayout

Tabs頁籤,效果類似網易新聞用戶端的Tab。其實實作Tabs頁籤的效果有很多中方法,Github上也有很多好

用的開源控件,隻是這次谷歌把它官方化了,使得開發者無需引用第三方庫,就能友善的使用。效果圖:

Android M新控件之FloatingActionButton,TextInputLayout,Snackbar,TabLayout的使用

XML布局如下:

<android.support.design.widget.TabLayout
        android:id="@+id/tabs"
    <!--Tab被選中字型的顔色-->
        app:tabSelectedTextColor="@android:color/holo_blue_bright"
    <!--Tab未被選中字型的顔色-->
        app:tabTextColor="@android:color/black"
    <!--Tab訓示器下标的顔色-->
        app:tabIndicatorColor="@android:color/holo_blue_bright"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
           

常用的屬性有三個:

  1. app:tabSelectedTextColor:Tab被選中字型的顔色
  2. app:tabTextColor:Tab未被選中字型的顔色
  3. app:tabIndicatorColor:Tab訓示器下标的顔色

TabLayout常用的方法如下:

- addTab(TabLayout.Tab tab, int position, boolean setSelected) 增加頁籤到 layout 中

- addTab(TabLayout.Tab tab, boolean setSelected) 同上

- addTab(TabLayout.Tab tab) 同上

- getTabAt(int index) 得到頁籤

- getTabCount() 得到頁籤的總個數

- getTabGravity() 得到 tab 的 Gravity

- getTabMode() 得到 tab 的模式

- getTabTextColors() 得到 tab 中文本的顔色

- newTab() 建立個 tab

- removeAllTabs() 移除所有的 tab

- removeTab(TabLayout.Tab tab) 移除指定的 tab

- removeTabAt(int position) 移除指定位置的 tab

- setOnTabSelectedListener(TabLayout.OnTabSelectedListener onTabSelectedListener) 為每個 tab 增加選擇監聽器

- setScrollPosition(int position, float positionOffset, boolean updateSelectedText) 設定滾動位置

- setTabGravity(int gravity) 設定 Gravity

- setTabMode(int mode) 設定 Mode,有兩種值:TabLayout.MODE_SCROLLABLE和TabLayout.MODE_FIXED分别表示當tab的内容超過螢幕寬度是否支援橫向水準滑動,第一種支援滑動,第二種不支援,預設不支援水準滑動。

- setTabTextColors(ColorStateList textColor) 設定 tab 中文本的顔色

- setTabTextColors(int normalColor, int selectedColor) 設定 tab 中文本的顔色 預設 選中

- setTabsFromPagerAdapter(PagerAdapter adapter) 設定 PagerAdapter

- setupWithViewPager(ViewPager viewPager) 和 ViewPager 關聯

一般TabLayout都是和ViewPager共同使用才發揮它的優勢,現在我們通過代碼來看看以上方法的使用。

viewPager = findView(R.id.viewPager);

        tabLayout = findView(R.id.tabs);
        List<String> tabList = new ArrayList<>();
        tabList.add("Tab1");
        tabList.add("Tab2");
        tabList.add("Tab3");
        tabLayout.setTabMode(TabLayout.MODE_FIXED);//設定tab模式,目前為系統預設模式
        tabLayout.addTab(tabLayout.newTab().setText(tabList.get()));//添加tab頁籤
        tabLayout.addTab(tabLayout.newTab().setText(tabList.get()));
        tabLayout.addTab(tabLayout.newTab().setText(tabList.get()));

        List<Fragment> fragmentList = new ArrayList<>();
        for (int i = ; i < tabList.size(); i++) {
            Fragment f1 = new TabFragment();
            Bundle bundle = new Bundle();
            bundle.putString("content", "http://blog.csdn.net/feiduclear_up \n CSDN 廢墟的樹");
            f1.setArguments(bundle);
            fragmentList.add(f1);
        }

        TabFragmentAdapter fragmentAdapter = new TabFragmentAdapter(getSupportFragmentManager(), fragmentList, tabList);
        viewPager.setAdapter(fragmentAdapter);//給ViewPager設定擴充卡
        tabLayout.setupWithViewPager(viewPager);//将TabLayout和ViewPager關聯起來。
        tabLayout.setTabsFromPagerAdapter(fragmentAdapter);//給Tabs設定擴充卡
           

就不解釋了,都有注釋,來看看以上代碼的TabFragmentAdapter和TabFragment實作如下:

TabFragmentAdapter

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);
    }
}
           

TabFragment

public class TabFragment extends Fragment {

    private String content;
    private View view;


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

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

注意 :有這麼一種情況,當Tabs中的内容超過了手機螢幕的寬度時,Tabs頁籤中的tab為什麼不支援水準滑動?其實TabLayout是支援水準滑動的,隻需要你在代碼中添加如下一行即可:

限于篇幅有點長,接下來的CoordinatorLayout , CollapsingToolbarLayout 和 AppBarLayout,NavigationView将

在下一篇部落格學習。以上代碼,如有疑問,歡迎共同讨論。

源碼位址 https://github.com/xujinping/AndroidDesignLibrary/tree/master

繼續閱讀