반응형

출처: 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 함수 내에서 처리 했지만, 입력받기 전 중 후로 처리를 할 수 있으니 잘 살펴 보길 바란다.

반응형

+ Recent posts