1. Giới thiệu
Các thành phần Material (MDC) giúp nhà phát triển triển khai Material Design. Do một nhóm kỹ sư và nhà thiết kế trải nghiệm người dùng (UX) tại Google tạo ra, MDC có hàng chục thành phần giao diện người dùng đẹp mắt và hữu ích, đồng thời có sẵn cho Android, iOS, web và Flutter.material.io/develop |
Material Design và các thành phần Material cho Android là gì?
Material Design là một hệ thống để xây dựng các sản phẩm kỹ thuật số nổi bật và đẹp mắt. Bằng cách kết hợp kiểu dáng, thương hiệu, tương tác và chuyển động theo một bộ nguyên tắc và thành phần nhất quán, các nhóm sản phẩm có thể hiện thực hoá tiềm năng thiết kế lớn nhất của mình.
Đối với các ứng dụng Android, Material Components for Android (MDC Android) kết hợp thiết kế và kỹ thuật với một thư viện các thành phần để tạo sự nhất quán trên ứng dụng của bạn. Khi hệ thống Material Design phát triển, các thành phần này sẽ được cập nhật để đảm bảo việc triển khai nhất quán, hoàn hảo đến từng pixel và tuân thủ các tiêu chuẩn phát triển giao diện người dùng của Google. MDC cũng có sẵn cho web, iOS và Flutter.
Trong lớp học lập trình này, bạn sẽ xây dựng một trang đăng nhập bằng cách sử dụng một số thành phần của MDC Android.
Sản phẩm bạn sẽ tạo ra
Lớp học lập trình này là lớp học đầu tiên trong số 4 lớp học lập trình hướng dẫn bạn xây dựng một ứng dụng có tên là Shrine, một ứng dụng Android thương mại điện tử bán quần áo và đồ gia dụng. Ứng dụng này sẽ minh hoạ cách bạn có thể tuỳ chỉnh các thành phần để phản ánh mọi thương hiệu hoặc kiểu dáng bằng MDC-Android.
Trong lớp học lập trình này, bạn sẽ xây dựng một trang đăng nhập cho Shrine có chứa:
- Hai trường văn bản, một trường để nhập tên người dùng và trường còn lại để nhập mật khẩu
- Hai nút, một nút "Huỷ" và một nút "Tiếp theo"
- Tên của ứng dụng (Shrine)
- Hình ảnh biểu trưng của Shrine

Các thành phần MDC Android trong lớp học lập trình này
- Trường văn bản
- Nút
Bạn cần có
- Kiến thức cơ bản về phát triển Android
- Android Studio (tải xuống tại đây nếu bạn chưa có)
- Một trình mô phỏng hoặc thiết bị Android (có sẵn thông qua Android Studio)
- Mã mẫu (xem bước tiếp theo)
Bạn đánh giá mức độ kinh nghiệm xây dựng ứng dụng Android của mình như thế nào?
2. Thiết lập môi trường phát triển
Khởi động Android Studio
Khi bạn mở Android Studio, ứng dụng này sẽ hiển thị một cửa sổ có tiêu đề "Welcome to Android Studio" (Chào mừng bạn đến với Android Studio). Tuy nhiên, nếu đây là lần đầu tiên bạn khởi chạy Android Studio, hãy thực hiện các bước trong Android Studio Setup Wizard (Trình hướng dẫn thiết lập Android Studio) với các giá trị mặc định. Bước này có thể mất vài phút để tải xuống và cài đặt các tệp cần thiết. Vì vậy, bạn có thể để quá trình này chạy trong nền trong khi thực hiện phần tiếp theo.
Tải ứng dụng khởi đầu cho lớp học lập trình xuống
Ứng dụng khởi đầu nằm trong thư mục material-components-android-codelabs-101-starter/java.
...hoặc sao chép ứng dụng này từ GitHub
Để sao chép lớp học lập trình này từ GitHub, hãy chạy các lệnh sau:
git clone https://github.com/material-components/material-components-android-codelabs cd material-components-android-codelabs/ git checkout 101-starter
Tải mã khởi đầu trong Android Studio
- Sau khi trình hướng dẫn thiết lập hoàn tất và cửa sổ Welcome to Android Studio (Chào mừng bạn đến với Android Studio) xuất hiện, hãy nhấp vào Open an existing Android Studio project (Mở một dự án Android Studio hiện có). Chuyển đến thư mục mà bạn đã cài đặt mã mẫu rồi chọn java -> shrine (hoặc tìm kiếm shrine trên máy tính) để mở dự án Shrine.
- Chờ một chút để Android Studio xây dựng và đồng bộ hoá dự án, như được biểu thị bằng các chỉ báo hoạt động dọc theo cuối cửa sổ Android Studio.
- Tại thời điểm này, Android Studio có thể đưa ra một số lỗi xây dựng vì bạn đang thiếu SDK Android hoặc các công cụ xây dựng, chẳng hạn như công cụ được hiển thị bên dưới. Hãy làm theo hướng dẫn trong Android Studio để cài đặt/cập nhật các công cụ này và đồng bộ hoá dự án của bạn.
Thêm các phần phụ thuộc của dự án
Dự án cần có một phần phụ thuộc vào thư viện hỗ trợ MDC Android. Mã mẫu mà bạn đã tải xuống sẽ có phần phụ thuộc này được liệt kê, nhưng bạn nên thực hiện các bước sau để đảm bảo.
- Chuyển đến tệp
build.gradlecủa mô-đunappvà đảm bảo rằng khốidependenciesbao gồm một phần phụ thuộc vào MDC Android:
api 'com.google.android.material:material:1.1.0-alpha06'
- (Không bắt buộc) Nếu cần, hãy chỉnh sửa tệp
build.gradleđể thêm các phần phụ thuộc sau và đồng bộ hoá dự án.
dependencies {
api 'com.google.android.material:material:1.1.0-alpha06'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.android.volley:volley:1.1.1'
implementation 'com.google.code.gson:gson:2.8.5'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.21"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:core:1.1.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test:runner:1.2.0-alpha05'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0-alpha05'
}
Chạy ứng dụng khởi đầu
|
Thành công! Mã khởi đầu cho trang đăng nhập của Shrine sẽ chạy trong trình mô phỏng của bạn. Bạn sẽ thấy tên "Shrine" và biểu trưng của Shrine ngay bên dưới.

Hãy xem mã. Chúng tôi đã cung cấp một khung điều hướng Fragment đơn giản trong mã mẫu để hiển thị các mảnh và di chuyển giữa các mảnh.
Mở MainActivity.java trong thư mục shrine -> app -> src -> main -> java -> com.google.codelabs.mdc.java.shrine. Tệp này sẽ chứa:
MainActivity.java
package com.google.codelabs.mdc.java.shrine;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity implements NavigationHost {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shr_main_activity);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.container, new LoginFragment())
.commit();
}
}
/**
* Navigate to the given fragment.
*
* @param fragment Fragment to navigate to.
* @param addToBackstack Whether or not the current fragment should be added to the backstack.
*/
@Override
public void navigateTo(Fragment fragment, boolean addToBackstack) {
FragmentTransaction transaction =
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment);
if (addToBackstack) {
transaction.addToBackStack(null);
}
transaction.commit();
}
}
Hoạt động này hiển thị tệp bố cục R.layout.shr_main_activity, được xác định trong shr_main_activity.xml.
Bạn có thể thấy rằng trong onCreate(), MainActivity.java bắt đầu một giao dịch Fragment để hiển thị LoginFragment. LoginFragment. Đây là nội dung mà chúng ta sẽ sửa đổi cho lớp học lập trình này. Hoạt động này cũng triển khai một phương thức navigateTo(Fragment), được xác định trong NavigationHost, cho phép mọi fragment di chuyển đến một fragment khác.
Command + Click (Lệnh + Nhấp) hoặc Control + Click (Ctrl + Nhấp) shr_main_activity trong tệp hoạt động để mở tệp bố cục hoặc chuyển đến tệp bố cục trong app -> res -> layout -> shr_main_activity.xml.
shr_main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />
Ở đây, chúng ta thấy một <FrameLayout> đơn giản đóng vai trò là vùng chứa cho mọi mảnh mà hoạt động hiển thị. Hãy mở LoginFragment.java.
LoginFragment.java
package com.google.codelabs.mdc.java.shrine;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
/**
* Fragment representing the login screen for Shrine.
*/
public class LoginFragment extends Fragment {
@Override
public View onCreateView(
@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.shr_login_fragment, container, false);
// Snippet from "Navigate to the next Fragment" section goes here.
return view;
}
// "isPasswordValid" from "Navigate to the next Fragment" section method goes here
}
LoginFragment mở rộng tệp bố cục shr_login_fragment và hiển thị tệp này trong onCreateView(). Hãy xem tệp bố cục shr_login_fragment.xml để biết trang đăng nhập trông như thế nào.
shr_login_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:background="@color/loginPageBackgroundColor"
tools:context=".LoginFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipChildren="false"
android:clipToPadding="false"
android:orientation="vertical"
android:padding="24dp"
android:paddingTop="16dp">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="48dp"
android:layout_marginBottom="16dp"
app:srcCompat="@drawable/shr_logo" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="132dp"
android:text="@string/shr_app_name"
android:textAllCaps="true"
android:textSize="16sp" />
<!-- Snippet from "Add text fields" section goes here. -->
<!-- Snippet from "Add buttons" section goes here. -->
</LinearLayout>
</ScrollView>
Ở đây, chúng ta có thể thấy một <LinearLayout> có <ImageView> ở trên cùng, đại diện cho biểu trưng "Shrine".
Sau đó, có một thẻ <TextView> đại diện cho nhãn "SHRINE". Văn bản cho nhãn này là một tài nguyên chuỗi có tên là @string/shr_app_name. Nếu bạn Command + Click (Lệnh + Nhấp) hoặc Control + Click (Ctrl + Nhấp) vào tên tài nguyên chuỗi hoặc mở app -> res -> values -> strings.xml, bạn có thể thấy tệp strings.xml nơi các tài nguyên chuỗi được xác định. Khi có thêm tài nguyên chuỗi được thêm vào trong tương lai, chúng sẽ được xác định ở đây. Mọi tài nguyên trong tệp này đều phải có tiền tố shr_ để biểu thị rằng chúng là một phần của ứng dụng Shrine.
Bây giờ bạn đã quen thuộc với mã khởi đầu, hãy triển khai thành phần đầu tiên.
3. Thêm trường văn bản
Để bắt đầu, chúng ta sẽ thêm hai trường văn bản vào trang đăng nhập để người dùng nhập tên người dùng và mật khẩu. Chúng ta sẽ sử dụng thành phần Trường văn bản MDC, bao gồm chức năng tích hợp hiển thị nhãn nổi và thông báo lỗi.

Thêm XML
Trong shr_login_fragment.xml, hãy thêm hai phần tử TextInputLayout có phần tử con TextInputEditText bên trong <LinearLayout>, bên dưới nhãn "SHRINE" <TextView>:
shr_login_fragment.xml
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:hint="@string/shr_hint_username">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/password_text_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:hint="@string/shr_hint_password">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/password_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
Đoạn mã trên đại diện cho hai trường văn bản, mỗi trường bao gồm một phần tử <TextInputLayout> và một phần tử con <TextInputEditText>. Văn bản gợi ý cho mỗi trường văn bản được chỉ định trong thuộc tính android:hint.
Chúng tôi đã thêm hai tài nguyên chuỗi mới cho trường văn bản – @string/shr_hint_username và @string/shr_hint_password. Mở strings.xml để xem các tài nguyên chuỗi này.
strings.xml
...
<string name="shr_hint_username">Username</string>
<string name="shr_hint_password">Password</string>
...
Thêm quy trình xác thực dữ liệu đầu vào
Các thành phần TextInputLayout cung cấp chức năng phản hồi lỗi tích hợp.
Để hiển thị phản hồi lỗi, hãy thực hiện các thay đổi sau đối với shr_login_fragment.xml:
- Đặt thuộc tính
app:errorEnabledthành true trên phần tử PasswordTextInputLayout. Thao tác này sẽ thêm khoảng đệm bổ sung cho thông báo lỗi bên dưới trường văn bản. - Đặt thuộc tính
android:inputTypethành "textPassword" trên phần tử PasswordTextInputEditText. Thao tác này sẽ ẩn văn bản nhập trong trường mật khẩu.
Với những thay đổi này, các trường văn bản trong shr_login_fragment.xml sẽ có dạng như sau:
shr_login_fragment.xml
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:hint="@string/shr_hint_username">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/password_text_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:hint="@string/shr_hint_password"
app:errorEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/password_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"/>
</com.google.android.material.textfield.TextInputLayout>
Bây giờ, hãy thử chạy ứng dụng. Bạn sẽ thấy một trang có hai trường văn bản cho "Tên người dùng" và "Mật khẩu"!
Xem ảnh động nhãn nổi:

4. Thêm nút
Tiếp theo, chúng ta sẽ thêm hai nút vào trang đăng nhập: "Huỷ" và "Tiếp theo". Chúng ta sẽ sử dụng thành phần Nút MDC, đi kèm với hiệu ứng gợn sóng mực Material Design mang tính biểu tượng được tích hợp sẵn.

Thêm XML
Trong shr_login_fragment.xml, hãy thêm một <RelativeLayout> vào <LinearLayout>, bên dưới các phần tử TextInputLayout. Sau đó, hãy thêm hai phần tử <MaterialButton> vào <RelativeLayout>.
Tệp XML kết quả sẽ có dạng như sau:
shr_login_fragment.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.button.MaterialButton
android:id="@+id/next_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:text="@string/shr_button_next" />
<com.google.android.material.button.MaterialButton
android:id="@+id/cancel_button"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="12dp"
android:layout_marginRight="12dp"
android:layout_toStartOf="@id/next_button"
android:layout_toLeftOf="@id/next_button"
android:text="@string/shr_button_cancel" />
</RelativeLayout>
Vậy là xong! Khi bạn chạy ứng dụng, một gợn sóng mực sẽ hiển thị khi bạn nhấn vào từng nút.

5. Di chuyển đến Mảnh tiếp theo
Cuối cùng, chúng ta sẽ thêm một số mã Java vào LoginFragment.java để kết nối nút "NEXT" (TIẾP THEO) với một fragment khác. Bạn sẽ nhận thấy rằng mỗi thành phần mà chúng ta thêm vào bố cục đều được gán một id. Chúng ta sẽ sử dụng các id này để tham chiếu các thành phần trong mã và thêm một số quy trình kiểm tra lỗi và điều hướng.
Hãy thêm một phương thức boolean riêng tư isPasswordValid trong LoginFragment.java bên dưới onCreateView(), với logic để xác định xem mật khẩu có hợp lệ hay không. Đối với mục đích của bản minh hoạ này, chúng ta chỉ cần đảm bảo rằng mật khẩu dài ít nhất 8 ký tự:
LoginFragment.java
/*
In reality, this will have more complex logic including, but not limited to, actual
authentication of the username and password.
*/
private boolean isPasswordValid(@Nullable Editable text) {
return text != null && text.length() >= 8;
}
Tiếp theo, hãy thêm một trình nghe lượt nhấp vào nút "Next" (Tiếp theo) để đặt và xoá lỗi dựa trên phương thức isPasswordValid() mà chúng ta vừa tạo. Trong onCreateView(), trình nghe lượt nhấp này phải được đặt giữa dòng trình mở rộng và dòng return view.
Tiếp theo, hãy thêm một trình nghe khoá vào mật khẩu TextInputEditText để nghe các sự kiện khoá sẽ xoá lỗi. Trình nghe này cũng phải sử dụng isPasswordValid() để kiểm tra xem mật khẩu có hợp lệ hay không. Bạn có thể thêm trình nghe này ngay bên dưới trình nghe lượt nhấp trong onCreateView().
Phương thức onCreateView() của bạn bây giờ sẽ có dạng như sau:
LoginFragment.java
@Override
public View onCreateView(
@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.shr_login_fragment, container, false);
final TextInputLayout passwordTextInput = view.findViewById(R.id.password_text_input);
final TextInputEditText passwordEditText = view.findViewById(R.id.password_edit_text);
MaterialButton nextButton = view.findViewById(R.id.next_button);
// Set an error if the password is less than 8 characters.
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!isPasswordValid(passwordEditText.getText())) {
passwordTextInput.setError(getString(R.string.shr_error_password));
} else {
passwordTextInput.setError(null); // Clear the error
}
}
});
// Clear the error once more than 8 characters are typed.
passwordEditText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if (isPasswordValid(passwordEditText.getText())) {
passwordTextInput.setError(null); //Clear the error
}
return false;
}
});
return view;
}
Bây giờ, chúng ta có thể di chuyển đến một fragment khác. Cập nhật OnClickListener trong onCreateView() để điều hướng đến một fragment khác khi quá trình xác thực lỗi thành công. Bạn có thể thực hiện việc này bằng cách thêm dòng sau để di chuyển đến ProductGridFragment cho trường hợp else của trình nghe lượt nhấp:
LoginFragment.java
...
((NavigationHost) getActivity()).navigateTo(new ProductGridFragment(), false); // Navigate to the next Fragment
...
Trình nghe lượt nhấp của bạn bây giờ sẽ có dạng như sau:
LoginFragment.java
...
MaterialButton nextButton = view.findViewById(R.id.next_button);
// Set an error if the password is less than 8 characters.
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!isPasswordValid(passwordEditText.getText())) {
passwordTextInput.setError(getString(R.string.shr_error_password));
} else {
passwordTextInput.setError(null); // Clear the error
((NavigationHost) getActivity()).navigateTo(new ProductGridFragment(), false); // Navigate to the next Fragment
}
}
});
...
Dòng mã mới này gọi phương thức navigateTo() từ MainActivity để điều hướng đến một fragment mới – ProductGridFragment. Hiện tại, đây là một trang trống mà bạn sẽ làm việc trong MDC-102.
Bây giờ, hãy xây dựng ứng dụng. Tiếp tục và nhấn vào nút Tiếp theo.
Thật tuyệt! Màn hình này sẽ là điểm xuất phát của lớp học lập trình tiếp theo mà bạn sẽ làm việc trong MDC-102.
6. Đã xong
Bằng cách sử dụng đánh dấu XML cơ bản và khoảng 30 dòng Java, thư viện Material Components for Android đã giúp bạn tạo một trang đăng nhập đẹp mắt tuân thủ các nguyên tắc Material Design, đồng thời có giao diện và hoạt động nhất quán trên tất cả các thiết bị.
Các bước tiếp theo
Trường văn bản và Nút là hai thành phần cốt lõi trong thư viện MDC Android, nhưng còn nhiều thành phần khác! Bạn có thể khám phá các thành phần còn lại trong MDC Android. Ngoài ra, hãy chuyển đến MDC 102: Cấu trúc và bố cục Material Design để tìm hiểu về thanh ứng dụng trên cùng, chế độ xem thẻ và bố cục lưới. Cảm ơn bạn đã dùng thử Material Components. Chúng tôi hy vọng bạn thích lớp học lập trình này!