Bài 11. findViewById trong Android


Trong Android, để truy suất tới các control bất kỳ ta có nhiều cách: Ta có thể dùng findViewById hoặc dùng ViewBinding.

Trong bài này Tui sẽ trình bày về kỹ thuật dùng findViewById, bài sau sẽ nói về ViewBinding.

Khi lập trình Android, để tương tác với các View/Control trong giao diện chúng ta thường thông qua thuộc tính Id của các view/control để truy suất thay đổi dữ liệu. Vì Android chia màn hình (Activity) thành hai phần: Phần thiết giao diện, phần xử lý nghiệp vụ. Do đó để truy suất được tới các View trong phần giao diện Android cung cấp hàm findViewById (Tạm thời nó sẽ không quen thuộc với những ai đi từ .Net dev qua, ở bài sau học ViewBinding các bạn sẽ thấy dễ chịu hơn):

Ta chú ý mỗi lần đặt Id cho bất kỳ một View nào đó thì Id này sẽ tự động được phát sinh ra trong lớp R của Android. Vì vậy khi truy suất tới View ta dùng R.id.idView.

Phiên bản cũ phải ép kiểu (ở trên thấy (Button)findViewById)

Phiên bản mới hơn 1 chút không cần ép kiểu

Phiên bản mới ta có thể dùng ViewBinding thay thế cho findViewById.

Ví dụ:

Tạo một dự án tên là “HocFindViewById” có giao diện như sau (cách tạo xem tại đây):

Cod XML layout như dưới đây:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="21dp"
        android:background="#FFEB3B"
        android:text="Mời bạn nhập số phone:"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/edtPhoneNumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="phone"
        android:text="0987773061"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        tools:layout_editor_absoluteX="74dp" />

    <Button
        android:id="@+id/btnCall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Gọi điện"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/edtPhoneNumber" />
</androidx.constraintlayout.widget.ConstraintLayout>

ở trên View/Control Edittext (để nhập liệu) ta đặt id là “edtPhoneNumber”, code bên dưới sẽ truy suất vào control Edittext dựa vào id này.

Bây giờ ta  bổ sung sự kiện cho nut Gọi điện, thêm thuộc tính android:conClick, đặt tên hàm bên trong:

Ví dụ ta đặt tên hàm là xuLyGoiDien, lúc này nó sẽ báo lỗi vì chưa được khai báo trong Java code, giờ ta làm cho nó tự động phát sinh mã lệnh như sau: Click chuột vào hàm, nó xổ ra cái bóng đèn, nhấn vào bóng đèn chọn -> Create ‘xuLyGoiDien(View)’ in ‘MainActivity’ (Hoặc bạn cũng có thể nhấn tổ hợp phím Alt+ Enter)

Lúc này MainActivity sẽ phát sinh ra một hàm xuLyGoiDien như dưới đây:

package tranduythanh.com.hocfindviewbyid;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void xuLyGoiDien(View view) {
       
    }

}

Bây giờ ta bổ sung mã lệnh cho hàm xuLyGoiDien:

public void xuLyGoiDien(View view) {
    //lệnh findViewById để truy suất tới control có id tương ứng truyền vào:
    EditText edtPhone=findViewById(R.id.edtPhoneNumber);
    //Lấy số phone ra:
    String phoneNumber=edtPhone.getText().toString();
    //Khai báo Intent để quay số gọi điện thoại
    Intent intent=new Intent(Intent.ACTION_DIAL);
    //Cú pháp gọi điện thoại
    Uri uri=Uri.parse("tel:"+phoneNumber);
    //gán uri cho intent:
    intent.setData(uri);
    //Gọi chức năng gọi điện thoại
    startActivity(intent);
}

Ở trên là hàm findViewById để truy suất vào control theo đúng id tương ứng truyền vào trong hàm. Với Android, mỗi lần 1 control được kéo thả vào màn hình, nó sẽ có 1 id, ta có thể sửa lại id hoặc đặt id mới. Thì Id này sẽ tự động được lưu trong file R (R là file tự động).

Android version mới không cần phải ép kiểu, nó tự tìm ra đúng kiểu control.

Chạy phần mềm lên ta được:

Như vậy Tui đã trình bày xong kỹ thuật dùng findViewById để truy suất tới các biến control trên giao diện, nó áp dụng cho mọi control nhé (Android họ thường gọi control là View).

coding tải ở đây: https://drive.google.com/open?id=1ADI-5lsDMgdnFjiNupIrPcoFbJszSjtO

Ở bài sau Tui sẽ hướng dẫn các bạn kỹ thuật dùng ViewBinding để truy suất trực tiếp vào các control mà không cần thông qua findViewById, giúp tiết kiệm thời gian hơn cho lập trình viên, cũng như làm quen thuộc hơn cho những ai đi từ .Net dev qua.

Các bạn chú ý làm lại bài này trước nhé, phải hiểu cơ chế hoạt động của nó, biết nhiều kỹ thuật để trong mọi trường hợp ta có thể áp dụng được các kỹ thuật khác nhau.

Các bạn chú ý theo dõi nhé

Chúc các bạn thành công

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.