我的CSDN博客同步發(fā)布:Material Design Library 使用匯總
轉(zhuǎn)載請注明出處:【huachao1001的簡書:http://www.reibang.com/users/0a7e42698e4b/latest_articles】
本文對Material Design Library
里面的庫類的使用做一個簡單的匯總,方便以后能快速查詢惯裕、快速上手使用寄症。本文包括以下內(nèi)容:
Color Palette
Toolbar
AppBarLayout
CollapsingToolbarLayout
CoordinatorLayout
DrawerLayout、NavigationView
Floating Action Button (FAB)
Snackbar
TabLayout
TextInputLayout
如有遺漏憔披,歡迎大家留言告知等限。我會持續(xù)補充,謝謝~活逆。
要使用Material Design Library
精刷,首先得將依賴庫加入到項目中,在app
的build.gradle
中(dependencies{ }
)蔗候,添加如下:
compile 'com.android.support:design:24.0.0'
1 Color Palette
我們可以定義狀態(tài)欄怒允、ActionBar
(或ToolBar
)、導(dǎo)航欄等等顏色锈遥∪沂拢可以通過如下方式:
修改res/values/styles.xml
文件如下:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
當(dāng)然了勘畔,可自定義的不僅僅就上面示例中的3
個,你還可以自定義如下圖所示的區(qū)域的顏色:
例如丽惶,你可以修改窗口背景色:
<item name="android:windowBackground">@color/colorAccent</item>
2 Toolbar炫七、AppBarLayout、CollapsingToolbarLayout
參考我的另一篇文章【玩轉(zhuǎn)AppBarLayout钾唬,更酷炫的頂部欄 】
3 CoordinatorLayout
參考我的另一篇文章【CoordinatorLayout的使用如此簡單 】
4 DrawerLayout万哪、NavigationView
在很多應(yīng)用中都使用到了Drawer
導(dǎo)航,在Design Support Library
中抡秆,提供了DrawerLayout
,看看如何使用的吧儒士!
首先的止,需要將android.support.v4.widget.DrawerLayout
作為布局的根標(biāo)簽,然后android.support.design.widget.NavigationView
作為其中的子標(biāo)簽着撩。如下所示:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="hello world!" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/drawer" />
</android.support.v4.widget.DrawerLayout>
NavigationView包含兩個引用诅福,一個是導(dǎo)航里面的頭部,另一個是菜單項拖叙,res/layout/drawer_header如下:
<?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="150dp"
android:background="?attr/colorPrimaryDark"
android:gravity="bottom"
android:orientation="vertical"
android:padding="16dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="頭部"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
</LinearLayout>
res/menu/drawer.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/home"
android:checked="true"
android:icon="@drawable/home"
android:title="主頁" />
<item
android:id="@+id/theme"
android:icon="@drawable/theme"
android:title="主題" />
<item
android:id="@+id/settings"
android:icon="@drawable/setting"
android:title="設(shè)置" />
</group>
<item android:title="二級菜單">
<menu>
<item
android:icon="@drawable/favorite"
android:title="收藏" />
<item
android:icon="@drawable/ablum"
android:title="相冊" />
<item
android:icon="@drawable/friends"
android:title="好友" />
</menu>
</item>
</menu>
然后氓润,可以在我們的Activity里面響應(yīng)菜單點擊:
public class MainActivity extends Activity
implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
}
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// int id = menuItem.getItemId();
String title = (String) menuItem.getTitle();
Toast.makeText(this, "您點擊了 " + title, Toast.LENGTH_SHORT).show();
return super.onContextItemSelected(menuItem);
}
}
效果如下:
5 Floating Action Button (FAB)
直接將android.support.design.widget.FloatingActionButton
放入布局中即可,例如憋沿,要放到右下:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="@dimen/activity_horizontal_margin"
android:layout_marginBottom="@dimen/activity_vertical_margin"
android:src="@drawable/ic_done" />
如果需要監(jiān)聽點擊旺芽,直接通過setOnclickListener即可:
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "您點擊了FAB", Toast.LENGTH_SHORT).show();
}
});
6 Snackbar
一般情況下,如果你想給用戶一個簡短的響應(yīng)反饋辐啄,我們會選擇使用Toast
采章,現(xiàn)在我們有了另一個選擇啦:Snackbar
。
看看如何使用
public void onClick(View v) {
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"您點擊了Snackbar中的確定", Toast.LENGTH_SHORT).show();
}
};
Snackbar sb = Snackbar.make(v,
"在這里是Snackbar顯示內(nèi)容",
Snackbar.LENGTH_LONG);
//添加點擊"按鈕"-->"確定"及其對應(yīng)的點擊事件
sb.setAction("確定", onClickListener);
//設(shè)置"確定"的顏色
sb.setActionTextColor(Color.RED);
//設(shè)置顯示消息的文字顏色
View view = sb.getView();
((TextView) view.findViewById(R.id.snackbar_text)).setTextColor(Color.GREEN);
//設(shè)置背景顏色
view.setBackgroundColor(Color.GRAY);
//設(shè)置透明度
view.setAlpha(0.5f);
//設(shè)置位置,Snackbar本質(zhì)是一個LinearLayout
ViewGroup.LayoutParams lp = view.getLayoutParams();
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(lp.width, lp.height);
llp.gravity = Gravity.TOP;
view.setLayoutParams(llp);
//顯示
sb.show();
}
看看效果:
7 TabLayout
先看布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.hc.materialdesign.MainActivity">
<android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
app:tabGravity="center"
app:tabMode="fixed" />
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
注意到壶辜,TabLayout中有兩個陌生的屬性
app:tabMode
:可以取如下兩個值悯舟,fixed
:表示Tab不能滾動scrollable
:表示Tab可以滾動,此時不管tabGravity取何值砸民,都是按照從左到右排過去抵怎,即相當(dāng)于app:tabGravity="left"
(當(dāng)然了,實際中沒有l(wèi)eft這個值岭参,只是我們可以這么去理解)app:tabGravity
:可以取如下兩個值反惕,fill
:當(dāng)tabMode取fixed時(即tab不能滾動時),tab的所有子標(biāo)簽填充tab的寬度center
:當(dāng)tabMode去fixed時演侯,tab中所有子標(biāo)簽居中顯示姿染。
為了有更加直觀的理解,看幾張圖片:
當(dāng)app:tabMode="scrollable"
:
當(dāng)app:tabMode="fixed"
且 app:tabGravity="center"
:
當(dāng)app:tabMode=fixed
且 app:tabGravity="fill"
:
好了秒际,接下來看看Activity里面具體代碼:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化ViewPager及其適配器
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
//將ViewPager與適配器關(guān)聯(lián)
viewPager.setAdapter(adapter);
//TabLayout
TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
//將ViewPager與TabLayout關(guān)聯(lián)
tabLayout.setupWithViewPager(viewPager);
//設(shè)置指示器的顏色
tabLayout.setSelectedTabIndicatorColor(Color.GREEN);
}
static class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return MyFragment.newInstance(position);
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
return "Tab " + position;
}
}
}
其中MyFragment很簡單悬赏,只是用于產(chǎn)生一個簡單的Fragment:
public class MyFragment extends Fragment {
private static final String TAB_POSITION = "tab_position";
public MyFragment() {
}
public static MyFragment newInstance(int tabPosition) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putInt(TAB_POSITION, tabPosition);
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
int tabPosition = args.getInt(TAB_POSITION);
TextView tv = new TextView(getActivity());
tv.setGravity(Gravity.CENTER);
tv.setText("Text in Tab #" + tabPosition);
return tv;
}
}
運行效果前面已經(jīng)貼出來了狡汉,這里就不再復(fù)制顯示了。
8 TextInputLayout
TextInputLayout
主要是用在登錄注冊方面闽颇。
先看看效果:
老規(guī)矩盾戴,從布局文件開始:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="@dimen/activity_vertical_margin"
tools:context="com.hc.materialdesign.MainActivity">
<android.support.design.widget.TextInputLayout
android:id="@+id/userName"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="用戶名"
android:inputType="textEmailAddress"
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="郵箱"
android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="login"
android:text="注冊" />
</LinearLayout>
可以看到,其實就是將我們平時用的Edit
控件放入到android.support.design.widget.TextInputLayout
里面,并且里面只能放一個Edit
,否則會報錯。這點讓我不太滿意,但是可是是在實現(xiàn)上放入多個Edit
不太好控制吧卒茬。
再看MainActivity對輸入框數(shù)據(jù)的驗證:
public class MainActivity extends AppCompatActivity {
TextInputLayout userNameWrapper;
TextInputLayout emailWrapper;
String emailFormate = "^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w+)+)$";
private Pattern pattern = Pattern.compile(emailFormate);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userNameWrapper = (TextInputLayout) findViewById(R.id.userName);
emailWrapper = (TextInputLayout) findViewById(R.id.email);
}
private boolean checkUserName() {
String userName = userNameWrapper.getEditText().getText().toString();
if (userName.trim().equals(""))
return false;
else
return true;
}
private boolean checkEmail() {
String email = emailWrapper.getEditText().getText().toString();
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
public void login(View v) {
View view = getCurrentFocus();
if (view != null) {
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
if (!checkUserName()) {
userNameWrapper.setError("用戶名不正確!");
} else {
userNameWrapper.setError("");
if (!checkEmail()) {
emailWrapper.setError("郵箱格式不正確躁绸!");
} else {
emailWrapper.setError("");
}
}
}
}
如果數(shù)據(jù)是錯誤的吮铭,我們只需通過setError
函數(shù)來顯示即可!
最后椎扬,可能你以及注意到惫搏,界面中,用到了各種顏色蚕涤。也就是說筐赔,里面的顏色我們是可以定制的,在你的style文件里面添加部分item即可:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<!-- Label color in TRUE state and bar color FALSE and TRUE State -->
<item name="colorAccent">#00ff00</item>
<item name="colorControlNormal">#00ffff</item>
<item name="colorControlActivated">#ff00ff</item>
<item name="android:textColorHint">#00ffff</item>
<item name="textColorError">#ff0000</item>
</style>
</resources>
參考資料:https://www.sitepoint.com/material-design-android-design-support-library/