Design Support Libraryでマテリアルデザインなアプリを作る
Design Support Libraryを使ってオシャレになろう!!
だいぶ遅れ気味ですが、Design Support Libraryを勉強してみたので、
簡単に使い方を紹介します。
build.gradleのdependenciesに以下を記載してください
compile 'com.android.support:design:22.2.+'
TextInputLayout
EditTextにhintを設定してもフォーカスを当てるとhintが消えてしまい、
何を入力すればいいのか分からなくなってしまいます。
そんな時の救世主がTextInputLayoutです。
フォーカスが当たるとhintがEditTextの上に表示されます。
また、エラー時はEditTextの下に表示する事も可能です。
使い方
layout.xml
<android.support.design.widget.TextInputLayout android:id="@+id/input_layout" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/edit" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="ヒント"/> </android.support.design.widget.TextInputLayout>
xmlはEditTextをTextInputLayoutで囲います。
hintの表示はこれだけでOKです。
エラーをEditText下部に表示したい場合は以下のようにします。
mTxtInputLayout.setError("エラーです。");
Snackbarを使う
Toastの進化形で、1つだけアクションを指定する事ができます。
削除ボタン⇒Snack通知(削除しました "取り消し")⇒削除取り消しなど
使い方
アクション無しの場合(Toastがオシャレになっただけ)
Snackbar.make(getView(), "削除しました", Snackbar.LENGTH_LONG).show();
Snackbar.make(getView(), "宝くじが当たりました", Snackbar.LENGTH_LONG) .setAction("だが断る", new View.OnClickListener() { @Override public void onClick(View v) { orz(); } }).show();
FloatingActionButtonを使う
Gmailの新規メールボタンのような右下に配置しているボタン
layout.xml
<android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" android:src="@android:drawable/ic_menu_camera" />
上記ではic_menu_cameraを指定しているので、カメラ画像のボタンが表示されます。
java側ではViewのOnClickListenerをセットすればいいのでbutton等と変わりません。
⇒butterknifeのOnClickアノテーションでもOKです。
注意点
FloatingActionButtonを使用している画面でSnackbarを出すとFloatingActionButtonが隠れてしまい、
Googleさん的には非推奨です。
なので、FloatingActionButtonを使用している画面のlayout.xmlの最上位はCoordinatorLayoutにします。
例
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> ~略~ </LinearLayout> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" android:src="@android:drawable/ic_menu_camera" /> </android.support.design.widget.CoordinatorLayout>
上記のようにCoordinatorLayoutで囲ってあげることで、
Snackbarが上がってきた分、FloatingActionButtonが上に移動してくれます。
子供が目を覚ましそうなので、今回はここまで