openplanning

Hướng dẫn và ví dụ Android Button

Xem thêm các chuyên mục:

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người.
Là một website được viết trên công nghệ web Flutter vì vậy hỗ trợ rất tốt cho người học, kể cả những người học khó tính nhất.
Hiện tại website đang tiếp tục được cập nhập nội dung cho phong phú và đầy đủ hơn. Mong các bạn nghé thăm và ủng hộ website mới của chúng tôi.
Hãy theo dõi chúng tôi trên Fanpage để nhận được thông báo mỗi khi có bài viết mới. Facebook

1- Android Button

Trong Android, Button là một "điều khiển giao diện người dùng" (user interface control), được sử dụng để thực hiện một hành động khi người dùng nhấp (click) vào nó.
Trên hệ thống phân cấp các lớp, Button là một lớp con của TextView, vì vậy nó thừa kế tất cả các tính năng của một TextView.
android:textAllCaps
Theo mặc định, khi hiển thị nội dung, văn bản của Button sẽ bị biến thành chữ hoa (uppercase), bạn nên sét đặt android:textAllCaps="false" để đảm bảo nội dung văn bản sẽ hiển thị đúng với nguyên bản.

<Button
    android:id="@+id/button3"
    android:text="Alarm"
    android:drawableLeft="@drawable/icon_alarm"
    android:textAllCaps="false"
    ... />
android:gravity
Thuộc tính android:gravity được sử dụng để sét đặt vị trí hiển thị văn bản của một Button. Giá trị của nó là kết hợp của các giá trị sau:
Constant in Java Value Description
Gravity.LEFT left  
Gravity.CENTER_HORIZONTAL center_horizontal  
Gravity.RIGHT right  
Gravity.CLIP_HORIZONTAL clip_horizontal  
Gravity.FILL_HORIZONTAL fill_horizontal  
     
Gravity.TOP top  
Gravity.CENTER_VERTICAL center_vertical  
Gravity.BOTTOM bottom  
Gravity.CLIP_VERTICAL clip_vertical  
Gravity.FILL_VERTICAL fill_vertical  
     
Gravity.START start  
Gravity.END end  
Gravity.CENTER center  
Gravity.FILL fill  

<Button
    android:id="@+id/button"
    android:gravity="center_horizontal|top"
    android:text="Text"
    ... />
Icon - android:drawableLef, android:drawableTop,..
Android cho phép bạn thêm 4 icon vào một Button thông qua các thuộc tính android:drawableLef, android:drawableTop, android:drawableRight, android:drawableBottom, android:drawableStart, android:drawableEnd.

<Button
    android:id="@+id/button"
    android:drawableLeft="@drawable/icon_bus"
    android:drawableTop="@drawable/icon_railway"
    android:drawableRight="@drawable/icon_car"
    android:drawableBottom="@drawable/icon_boat"
    android:text="Text"
    ...  />
Android 4.1 bắt đầu hỗ trợ sự khác biệt về bố cục văn bản giữa các ngôn ngữ khác nhau. Cụ thể với tiếng Anh, văn bản có hướng từ trái sang phải, trong khi với các ngôn ngữ Ả Rập văn bản có hướng từ phải sang trái.
LTR (Left to Right)
Trong chế độ bố cục LTR (Left to Right): Thuộc tính android:drawableStart sẽ làm việc giống với android:drawableLeft, và android:drawableEnd sẽ làm việc giống với android:drawableRight.
RTL (Right to Left)
Trong chế độ bố cục RTL (Right to Left): Thuộc tính android:drawableStart sẽ làm việc giống với android:drawableRight, và android:drawableEnd sẽ làm việc giống với android:drawableStart.
  • TODO Link?

2- Button Click Event

Sự kiện Click (Nhấp) xẩy ra sau khi người dùng nhấn xuống (Press down) và nhả (Release) ra khỏi Button.
Bạn có thể định nghĩa tên của phương thức sẽ được gọi khi người dùng nhấp (click) vào Button bằng cách sử dụng thuộc tính android.onClick.

<Button
    android:id="@+id/button_clickMe"
    android:onClick="onClickHandler"
    android:text="Click Me"
    ... />
Đồng thời tạo phương thức này trong lớp MainActivity.

// MainActivity

public void onClickHandler(View view)  {
    Toast.makeText(this, "You click on 'Click Me' button!", Toast.LENGTH_SHORT).show();
}
Bạn cũng có thể định nghĩa phương thức sẽ được gọi khi người dùng nhấp vào Button, hoàn toàn với mã Java:

this.buttonClickMe = (Button) this.findViewById(R.id.button_clickMe);

this.buttonClickMe.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, "You click on 'Click Me' button!", Toast.LENGTH_SHORT).show();
    }
});

3- Button Long Click Event

Sự kiện Long Click (Nhấp dài) trong Android xẩy ra khi người dùng nhấn xuống (Press down) View và giữ như vậy trong khoảng thời gian dài. Cụ thể, sự kiện sẽ xẩy ra tại thời điểm LONG_PRESS_TIMEOUT mili giây kể từ khi người dùng nhấn xuống (Press down). Bạn có thể có được giá trị của LONG_PRESS_TIMEOUT từ phương thức ViewConfiguration.getLongPressTimeout().
Khoảng thời gian mặc định của một cú nhấp dài (Long-Click) trong AndroidDEFAULT_LONG_PRESS_TIMEOUT mili giây. Người dùng có thể thay đổi thời gian cho một cú nhấp dài (Long-Click) trong mục Settings của thiết bị, nó sẽ có tác dụng với tất cả các ứng dụng trọng hệ thống. Các nhà phát triển ứng dụng không thể thay đổi giá trị này.
Constant
(private)
Method
Value
(Milliseconds)
DEFAULT_LONG_PRESS_TIMEOUT   500
  ViewConfiguration.getLongPressTimeout() 500 (default)
Ví dụ: Xử lý sự kiện khi người dùng Long Click (Nhấp dài) vào một Button bằng mã Java (Chú ý bạn không thể thực hiện điều này với XML).

this.buttonClickMe = (Button) this.findViewById(R.id.button_clickMe);


this.buttonClickMe.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        Toast.makeText(MainActivity.this, "You long click on 'Click Me' button!", Toast.LENGTH_SHORT).show();
        return true;
    }
});
Nếu người dùng nhấp (click) vào View trong một khoảng thời gian dài (Lớn hơn LONG_PRESS_TIMEOUT mili giây), nó có thể tạo ra 2 sự kiện liên tiếp là Long-ClickClick.
Phương thức onLongClick(View) trả về một giá trị boolean. Nếu trả về true nghĩa là bạn đã tiêu thụ sự kiện Long-Click, và sự kiện Click xẩy ra sau đó sẽ bị bỏ qua. Ngược lại nếu phương thức onLongClick(View) trả về giá trị false, điều đó có nghĩa là sự kiện Click xẩy ra sau đó sẽ được thực thi.

4- Ví dụ Android Button

Đây là một ví dụ đơn giản, người dùng sẽ nhập vào 2 số, và nhấn Button để tính tổng 2 số này.
Thiết kế giao diện của ví dụ:
Căn chỉnh vị trí các thành phần trên giao diện:
Sét đặt ID, Text cho các thành phần trên giao diện:
activity_main.xml

<?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="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Number 1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText_number1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:ems="10"
        android:inputType="number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Number 2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_number1" />

    <EditText
        android:id="@+id/editText_number2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:ems="10"
        android:inputType="number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <Button
        android:id="@+id/button_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Add"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_number2" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java

package org.o7planning.buttonexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private EditText editTextNumber1;
    private EditText editTextNumber2;
    private Button buttonAdd;

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

        this.editTextNumber1 = (EditText) this.findViewById(R.id.editText_number1);
        this.editTextNumber2 = (EditText) this.findViewById(R.id.editText_number2);

        this.buttonAdd = (Button) this.findViewById(R.id.button_add);

        this.buttonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                add2Number();
            }
        });
    }


    private void add2Number()  {
        String str1 = this.editTextNumber1.getText().toString();
        String str2 = this.editTextNumber2.getText().toString();
        try {
            double value1 = Double.parseDouble(str1);
            double value2 = Double.parseDouble(str2);

            double result = value1 + value2;

            Toast.makeText(this, "Result: " + result, Toast.LENGTH_SHORT).show();
        } catch(Exception e)  {
            Toast.makeText(this, "Error: "+ e, Toast.LENGTH_SHORT).show();
        }
    }

}

Xem thêm các chuyên mục: