Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách sử dụng equals() trong TextView Android

Giới thiệu

Ví dụ này minh họa cách sử dụng phương thức equals() để so sánh chuỗi phân biệt chữ hoa/chữ thường trong Android.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:hint="Nhập tên"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/click"
        android:text="Nhấn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:textSize="25sp"
        android:layout_height="wrap_content" />
</LinearLayout>

Bước 3: Viết logic (src/MainActivity.java)

package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    EditText name;
    Button button;
    TextView text;

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

        name = findViewById(R.id.name);
        button = findViewById(R.id.click);
        text = findViewById(R.id.textview);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = name.getText().toString();
                if (!input.isEmpty()) {
                    // So sánh chính xác (phân biệt hoa/thường) với "point"
                    boolean result = input.equals("point");
                    text.setText(String.valueOf(result));
                } else {
                    name.setError("Vui lòng nhập tên");
                }
            }
        });
    }
}

Phương thức equals() trả về true chỉ khi hai chuỗi giống hệt nhau bao gồm cả chữ hoa/chữ thường.

Chạy ứng dụng

Nhập "point" (viết thường) → true. Nhập "POINT" hoặc chuỗi khác → false.

Cách sử dụng equals() trong TextView Android

Cách sử dụng equals() trong TextView Android