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

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

Giới thiệu

Ví dụ này minh họa cách sử dụng phương thức equalsIgnoreCase() để so sánh hai chuỗi không 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 không phân biệt hoa/thường với chuỗi "point"
                    boolean result = input.equalsIgnoreCase("point");
                    text.setText(String.valueOf(result));
                } else {
                    name.setError("Vui lòng nhập tên");
                }
            }
        });
    }
}

Phương thức equalsIgnoreCase() trả về true nếu hai chuỗi bằng nhau về mặt nội dung, bỏ qua chữ hoa/chữ thường.

Chạy ứng dụng

Nhập "POINT" (viết hoa) → kết quả true. Nhập chuỗi khác không chứa "point" → kết quả false.

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

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