Material Design (Lecture 15 – material design)

Post on 28-Jan-2018

186 views 0 download

Transcript of Material Design (Lecture 15 – material design)

Material DesignAndroid

Константин Золотов

Темное прошлое Google

Проект Кеннеди 2011

Material design 2014

Основные принципы

Тактильные поверхности

Даешь простоту и "чистый" дизайн!

Material application

Контрастная журнальная типографикаМодульная сетка (Базовая сетка в 8dp и отступ слева в 72dp)Геометрическая иконографикаТениЦветаMaterial компоненты

Material

Материал является частью пространства с рядом свойств.Большая часть свойств перенеса из реального трехмерного

мира.

Тени отбрасываются элементами находящимися вышеМатериалы не могут занимать одно и то же место в пространствеМатериалы не могут проходить друг через другаМатериалы не могут сгибатьсяМатериалы могут менять формуНесколько материалов могут объединяться в одинМатериал может разделяться на несколько частей

Тени

Тени явно указывают на границы материала

Z = elevation + translationZ

android:elevation="2dp"

Глубина

Плавающие кнопки, тулбары и диалоговые окна находятся на определенной высоте. Иногдаим нужно перемещаться по оси Z, чтобы избегать столкновений, когда что-то происходит. С

этой хореографией нужно быть предельно внимательным.

Анимации

Естественное ускорение нелинейноМатериалы "отвечают" на взаимодействиеАнимации перехода удерживают и акцентируют внимание пользователяАнимации деталей

Движение

Используется для удержания фокуса на важных элементахПоказывает, что произойдет при действииОвлечение внимания от того, что происходит "под капотом"

Как движется

Движение используется для демонстрации связиДвижение следует таковому в реальном мире (гравитация, трение, и т.д.)Учитывает окружениеИспользует интерполяторы для нелинейного и естественного ускорения и замедления

Интересные детали

Можно делать интересные пасхалки (превращение "гамбургера" в стрелочку)Объекты, ведущие себя как настоящие (открывающийся конверт, перелистываниекалендаря)Иллюстрации

Цвета

Создание цветовой палитры для приложенияИспользовать доп. цвета только когда нет подходящих в палитреДержать список цветов максимально короткимНе создавать новый ресурс, если он не будет использоваться

Палитра

Material design palette generator

1 <resources> 2 <color name="primary">#4CAF50</color> 3 <color name="primary_dark">#388E3C</color> 4 <color name="primary_light">#C8E6C9</color> 5 <color name="accent">#ff813aff</color> 6 <color name="secondary_text">#727272</color> 7 <color name="icons">#FFFFFF</color> 8 <color name="divider">#B6B6B6</color> 9 </resources>

App Style 1 <resources> 2 <style name="AppTheme" parent="Theme.AppCompat"> 3 <item name="windowActionBar">false</item> 4 <item name="windowNoTitle">true</item> 5 <item name="colorPrimary">#009688</item> 6 <item name="colorPrimaryDark">#00796B</item> 7 <item name="colorEdgeEffect">?attr/colorPrimary</item> 8 <item name="colorAccent">#B2DFDB</item> 9 <item name="android:textColorPrimary">#fff</item> 10 </style>11 </resources>

Palette

compile 'com.android.support:palette-v7:24.0.0'

1 Palette p = Palette.generate(bitmap); 2 Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() { 3 @Override4 public void onGenerated(Palette palette) { 5 } 6 }); 7 8 int vibrant = palette.getVibrantColor(0x000000);9 int vibrantLight = palette.getLightVibrantColor(0x000000);

Android Design Support Library

Новая библиотека поддержки Android Design Support Library делает доступным весь наборкомпонентов материального дизайна для всех версий, начиная с Android 2.1 и выше:

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

Navigation View (для Navigation Drawer) — панель навигацииFloating Labels (для EditText) — плавающий ярлыкFloating Action Button (FAB) плавающая кнопкаSnackbar — всплывающее уведомление с кнопкойTabs — вкладкиMotion and Scroll framework — управление жестами и прокруткой

Floating Labels

1 <android.support.design.widget.TextInputLayout 2 android:layout_width="match_parent" 3 android:layout_height="wrap_content"> 4 <EditText 5 android:layout_width="match_parent" 6 android:layout_height="wrap_content" 7 android:hint="hint" 8 android:id="@+id/editText1" /> 9 </android.support.design.widget.TextInputLayout>

setErrorEnabled(true); setError(getString(R.string.text_error_message));

Floating Action Button (FAB)

Normal (56dp) Mini (40dp)

1 <android.support.design.widget.FloatingActionButton 2 android:id=”@+id/fab_normal” 3 android:layout_width=”wrap_content” 4 android:layout_height=”wrap_content” 5 android:src=”@drawable/ic_plus” 6 app:backgroundTint="@color/red" 7 app:rippleColor="@color/white" 8 app:fabSize=”normal” />

Snackbar

1 Snackbar2 .make(parentLayout, R.string.snackbar_text, Snackbar.LENGTH_LONG)3 .setAction(R.string.snackbar_action, myOnClickListener)4 .show(); // Don’t forget to show!

Coordinator Layout

1 <android.support.design.widget.CoordinatorLayout 2 android:id="@+id/main_content"> 3 <!-- Your other views --> 4 <android.support.design.widget.FloatingActionButton 5 android:id=”@+id/fab_normal” 6 android:layout_width=”wrap_content” 7 android:layout_height=”wrap_content” 8 android:src=”@drawable/ic_plus” 9 android:layout_gravity="bottom|right" 10 app:fabSize=”normal” /> 11 </android.support.design.widget.CoordinatorLayout>

Snackbar.make(mCoordinator, "Your message", Snackbar.LENGTH_SHORT) .show();

Card View 1 <android.support.v7.widget.CardView 2 xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 app:contentPadding="8dp" 7 app:cardUseCompatPadding="true" > 8 9 <LinearLayout 10 android:layout_width="match_parent" 11 android:layout_height="match_parent" 12 android:orientation="vertical" > 13 14 <TextView 15 android:id="@+id/title" 16 android:layout_width="match_parent" 17 android:layout_height="wrap_content" 18 android:singleLine="true" 19 style="@style/Base.TextAppearance.AppCompat.Headline" /> 20 21 <TextView 22 android:id="@+id/subtitle" 23 android:layout_width="match_parent"

Recycler View

Ключевые моменты:

Adapter (аналогично ListView)ItemAnimator (удаление, добавление, изменение)ItemDecoration (добавление разделителей)LayoutManager (LinearLayoutManager, GridLayoutManager, StaggeredGridLayoutManager)ViewHolder patternRecyclerView объединяет все воедино

Butterknife

Объявление

compile 'com.jakewharton:butterknife:8.2.1'

lintOptions { disable 'InvalidPackage' }

Инициализации View

Activity

1 @BindView(R.id.title) 2 TextView title; 3 @BindView(R.id.subtitle) 4 TextView subtitle; 5 6 private Unbinder unbinder; 7 8 @Override 9 public void onCreate(Bundle savedInstanceState) { 10 super.onCreate(savedInstanceState); 11 setContentView(R.layout.simple_activity); 12 unbinder = ButterKnife.bind(this); 13 // TODO Use fields... 14 } 15 16 @Override 17 public void onDestroy() { 18 unbinder.unbind(); 19 super.onDestroy(); 20 }

Инициализации View

Fragment

1 @BindView(R.id.button1) 2 Button button1; 3 @BindView(R.id.button2) 4 Button button2; 5 6 private Unbinder unbinder; 7 8 @Override 9 public View onCreateView(LayoutInflater inflater, 10 ViewGroup container, Bundle savedInstanceState) { 11 View view = inflater.inflate(R.layout.fragment, container, false); 12 unbinder = ButterKnife.bind(this, view); 13 // TODO Use fields... 14 return view; 15 } 16 17 @Override 18 public void onDestroyView() { 19 unbinder.unbind(); 20 super.onDestroyView(); 21 }

ButterKnife в адаптерах 1 static class ViewHolder { 2 @BindView(R.id.title) 3 TextView name; 4 5 @BindView(R.id.job_title) 6 TextView jobTitle; 7 8 public ViewHolder(View view) { 9 ButterKnife.bind(this, view); 10 } 11 }

События 1 @OnClick(R.id.submit) 2 public void submit() { 3 } 4 5 @OnClick(R.id.submit) 6 public void sayHi(Button button) { 7 button.setText("Hello!"); 8 } 9 10 @OnItemSelected(R.id.list_view) 11 void onItemSelected(int position) { 12 }

Опциональные1 @Nullable 2 @Bind(R.id.might_not_be_there) 3 TextView mightNotBeThere; 4 5 @Nullable 6 @OnClick(R.id.maybe_missing) 7 public void onMaybeMissingClicked() { 8 }

Destroy1 @Override 2 public void onDestroyView() { 3 super.onDestroyView(); 4 ButterKnife.unbind(this); 5 }

Полезные ссылки

Material design aboutMaterial design iconsMaterial design palette generatorButterKnife