TextWatcher 를 이용한 글입력 제한 하기.

2015. 4. 11. 17:48·IT기술 관련/모바일
반응형

출처: http://ememomo.tistory.com/36


/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.text;

/**
 * When an object of a type is attached to an Editable, its methods will
 * be called when the text is changed.
 */
public interface TextWatcher extends NoCopySpan {
    /**
     * This method is called to notify you that, within <code>s</code>,
     * the <code>count</code> characters beginning at <code>start</code>
     * are about to be replaced by new text with length <code>after</code>.
     * It is an error to attempt to make changes to <code>s</code> from
     * this callback.
     */
    public void beforeTextChanged(CharSequence s, int start,
                                  int count, int after);
    /**
     * This method is called to notify you that, within <code>s</code>,
     * the <code>count</code> characters beginning at <code>start</code>
     * have just replaced old text that had length <code>before</code>.
     * It is an error to attempt to make changes to <code>s</code> from
     * this callback.
     */
    public void onTextChanged(CharSequence s, int start, int before, int count);

    /**
     * This method is called to notify you that, somewhere within
     * <code>s</code>, the text has been changed.
     * It is legitimate to make further changes to <code>s</code> from
     * this callback, but be careful not to get yourself into an infinite
     * loop, because any changes you make will cause this method to be
     * called again recursively.
     * (You are not told where the change took place because other
     * afterTextChanged() methods may already have made other changes
     * and invalidated the offsets.  But if you need to know here,
     * you can use {@link Spannable#setSpan} in {@link #onTextChanged}
     * to mark your place and then look up from here where the span
     * ended up.
     */
    public void afterTextChanged(Editable s);
}


TextWatcher 인터페이스를 보면 beforeTextChanged / onTextChanged /  afterTextChanged 함수를 오버라이딩 하여야 한다.

각각의 함수는 이름을 보면 대충 언제 구동되는지 알 수 있을 것이다. 

이 인터페이스를 이용해서 입력값에 대한 실시간 변화를 감지해 낼 수 잇다. 예를 들어 가격을 입력하는 창이라던지, 글자를 

입력하는 창에서 조건을 걸어 검사를 할때 유용하게 사용 할 수 있다. 

이번예제는 TextWatcher 인터페이스를 이용해서 글자수를 제한 해 보는 예제이다. 

하나의 입력창이 있고 , 그 입력창을 글자수를 실시간으로 반영 하며, 50자 이상일때 입력을 제한하는 Toast 메시지를 띄우는 

예제이다.

화면을 살펴 보면 


이런식의 예제이다. 이를 응용하면 가격표에 자동으로 , 표시를 추가하는등의 함수도 작성 할 수 있다.

쓰는 법은 간단하니 코드를 살펴 보자. 


main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical"
 android:background="#ffffff"
 android:gravity="center"
 >
 <LinearLayout
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal">
  <TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_marginLeft="9dip"
   android:layout_marginTop="10dip" />
  <TextView
   android:id="@+id/review_length"
   android:layout_marginTop="15dip"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:paddingRight="5dip"
   android:layout_marginLeft="240dip"
   android:text="0/50자" />
 </LinearLayout>
 <EditText
  android:id="@+id/estimate_review_content"
  android:layout_marginLeft="8dip"
  android:layout_marginTop="1dip"
  android:maxLength="50"
  android:padding="7dip"
  android:layout_width="200dip"
  android:layout_height="75dip" />
</LinearLayout>



Strudy_0522.java

package com.tistory.ememomo;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Strudy_0522 extends Activity implements TextWatcher{
    
 private EditText   review_content;
    private TextView  review_length;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        review_content     = (EditText) findViewById(R.id.estimate_review_content);
        review_length     = (TextView) findViewById(R.id.review_length);
        review_content.addTextChangedListener(this);
    }
    
    @Override
 public void afterTextChanged(Editable s) {
  
 }
 @Override
 public void beforeTextChanged(CharSequence s, int start, int count,
   int after) {
  
 }
 @Override
 public void onTextChanged(CharSequence s, int start, int before, int count) {
  
  if(s.length() >= 50)
  {
   Toast.makeText(Strudy_0522.this, "글은 50자 까지 입력 가능합니다.", Toast.LENGTH_SHORT).show();
  }
  review_length.setText( s.length() + "/50자");
 }
}



EditText 입력창에 addTextChangedListener 리스너를 달아 주고 그 리스너를 이용하는건 TextView에다 넘겨주었다.

내가 처리한곳은 onTextChanged 함수 내에서 처리 했지만, 입력받기 전 중 후로 처리를 할 수 있으니 잘 살펴 보길 바란다.

반응형
저작자표시 (새창열림)

'IT기술 관련 > 모바일' 카테고리의 다른 글

[Android] “gradle DSL method not found: android()” 해결하기  (0) 2015.12.23
[Android] failed to find target android-21 오류 해결하기  (0) 2015.12.18
스마트폰의 센서 종류와 특징 그리고 활용의 예  (0) 2015.10.18
TextWatcher 설명  (0) 2015.04.11
모바일 챌린저  (0) 2015.02.21
'IT기술 관련/모바일' 카테고리의 다른 글
  • [Android] failed to find target android-21 오류 해결하기
  • 스마트폰의 센서 종류와 특징 그리고 활용의 예
  • TextWatcher 설명
  • 모바일 챌린저
호레
호레
창업 / IT / 육아 / 일상 / 여행
    반응형
  • 호레
    Unique Life
    호레
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 법률
        • 기본
        • 개인정보보호법
        • 정보통신망법
        • 전자금융거래법
        • 전자금융감독규정
        • 신용정보법
        • 온라인투자연계금융업법
      • 창업
        • 외식업 관련
        • 임대업 관련
        • 유통업 관련
        • 세무 관련
        • 마케팅 관련
        • 기타 지식
        • 트렌드
        • Youtube
      • IT기술 관련
        • 모바일
        • 윈도우
        • 리눅스
        • MAC OS
        • 네트워크
        • 빅데이터 관련
        • A.I 인공지능
        • 파이썬_루비 등 언어
        • 쿠버네티스
        • 기타 기술
      • 퍼블릭 클라우드 관련
        • Azure
        • GCP
        • AWS
      • 정보보안 관련
        • QRadar
        • Splunk
        • System
        • Web
      • 기타
        • 세상 모든 정보
        • 서적
      • 게임 관련
        • 유니티
      • 부동산
      • 맛집 찾기
        • 강남역
        • 양재역
        • 판교역
        • ★★★★★
        • ★★★★
        • ★★★
        • ★★
        • ★
      • 결혼_육아 생활
        • 리얼후기
        • 일상
        • 육아
        • 사랑
        • Food
      • 영어
        • 스피킹
        • 문법
        • 팝송
        • 영화
      • K-컨텐츠
        • 드라마
        • 영화
        • 예능
      • 독서
      • 프로젝트 관련 조사
        • 시스템 구축
        • 로그 관련
        • 웹
        • APT
        • 모의 해킹
        • DB
        • 허니팟
        • 수리카타
        • 알고리즘
        • FDS
      • 기업별 구내 식당 평가
        • 한국관광공사
        • KT telecop
        • KT M&S
        • KT powertel
        • KT cs 연수원
        • 진에어
      • 대학 생활
        • 위드윈연구소
        • 진로 고민
        • 채용정보
        • 자동차
        • 주식
        • 악성코드
        • 게임 보안
      • 쉐어하우스
  • 블로그 메뉴

    • 홈
    • 게임 관련
    • IT 기술 관련
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    돈까스
    무역전쟁
    수제버거
    판교
    마케팅
    수제버거맛집
    이재곧죽습니다
    쥬쥬랜드
    맛집
    런치
    상호관세
    AWS
    판교맛집
    복리후생
    점심
    대통령
    보안가이드
    판교역
    수제버거존맛
    유니티
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
호레
TextWatcher 를 이용한 글입력 제한 하기.

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.