상세 컨텐츠

본문 제목

[안드로이드] 텍스트(EditText) 입력 체크 및 버튼(Button) 활성화

안드로이드

by aries574 2021. 1. 1. 16:28

본문


2020/12/31 - [안드로이드] - [안드로이드] Notification 커스텀 알림창 쉽게 적용해보기


이번 시간에는 사용자가 텍스트를 입력해야 버튼을 클릭할 수 있게 하는 간단한 예제입니다.


1. 메인화면 구현(activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

<EditText
android:id="@+id/eMessage"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_above="@+id/button"/>

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="메시지 띄우기"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>


2. 메인코드 구현(MainActivity.java)


import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

EditText eMessage;
Button btn;
String message;

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

btn = findViewById(R.id.button);
eMessage = findViewById(R.id.eMessage);

//버튼 기본 비활성화 상태
btn.setEnabled(false);

//에디트텍스트 텍스트변경시 호출
eMessage.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

message = eMessage.getText().toString();
if(message.length() == 0){
btn.setEnabled(false);
}else{
btn.setEnabled(true);
}
}

@Override
public void afterTextChanged(Editable s) {

}
});

//버튼 클릭시 호출
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
});
}
}


3. 실행화면



반응형

관련글 더보기

댓글 영역