Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 TextView에서 replaceAll() 메서드 사용하는 방법

안드로이드 TextView에서 replaceAll() 활용하기

이 예제에서는 안드로이드 TextView에서 replaceAll() 메서드를 사용하는 방법을 단계별로 알아봅니다. replaceAll()은 문자열에서 특정 패턴과 일치하는 모든 부분을 다른 문자열로 교체할 때 사용하는 강력한 메서드입니다.

1단계: 새 프로젝트 생성

Android Studio에서 새 프로젝트를 생성합니다. 상단 메뉴에서 File ⇒ New Project로 이동한 후, 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.

2단계: 레이아웃 파일 작성

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="Enter name"
      android:layout_height="wrap_content" />
   <Button
      android:id="@+id/click"
      android:text="Click"
      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>

위 코드에서는 이름을 입력받는 EditText를 배치했습니다. 사용자가 버튼을 클릭하면 입력된 데이터를 가져와 공백을 빈 문자열로 교체하게 됩니다.

3단계: 메인 액티비티 코드 작성

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) {
            if (!name.getText().toString().isEmpty()) {
               if (name.getText().toString().length() >= 0) {
                  String replace = name.getText().toString().replaceAll("\\s","");
                  text.setText(String.valueOf(replace));
               }
            } else {
               name.setError("Plz enter name");
            }
         }
      });
   }
}

애플리케이션 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run 아이콘을 클릭합니다. 모바일 기기를 선택하면 앱이 실행되고, 기기에 기본 화면이 표시됩니다.

안드로이드 TextView에서 replaceAll() 메서드 사용하는 방법

위 결과에서 입력란에 "Krishna sai sai"라는 문자열을 입력한 경우를 볼 수 있습니다. 버튼을 클릭하면 replaceAll("\\s", "") 정규식 패턴을 통해 모든 공백 문자가 빈 문자열로 교체되어 "Krishnasaisai"로 표시됩니다. 여기서 \\s는 공백, 탭 등 모든 종류의 공백 문자를 의미하는 정규식 패턴입니다.