EditText의 라이브 문자 수


101

Android에서 편집 텍스트 상자의 라이브 문자 수를 계산하는 가장 좋은 방법이 무엇인지 궁금합니다. 나는 이것을 보고 있었지만 이해가되지 않는 것 같았다.

문제를 설명하기 위해 EditText가 있고 문자를 150 자로 제한하려고합니다. 입력 필터로이 작업을 수행 할 수 있지만 텍스트 상자 바로 아래에 사용자가 입력 한 문자 수를 표시하고 싶습니다 (거의 스택 오버플로가 지금하고있는 것처럼).

누군가가 예제 코드의 작은 스 니펫을 작성하거나 올바른 방향으로 나를 가리킬 수 있다면 정말 감사하겠습니다.

답변:


153

TextWatcher를 사용하여 텍스트가 언제 변경되었는지 확인할 수 있습니다.

private TextView mTextView;
private EditText mEditText;
private final TextWatcher mTextEditorWatcher = new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
           //This sets a textview to the current length
           mTextView.setText(String.valueOf(s.length()));
        }

        public void afterTextChanged(Editable s) {
        }
};

편집 텍스트에 대한 TextWatcher를 설정합니다.

mEditText.addTextChangedListener(mTextEditorWatcher);

5
이것을 시도, 훌륭하게 작동합니다! 정답으로 선택해야합니다!
Patrick Boos 2011 년

2
카운트를 추가하는 가장 좋은 방법은 텍스트 상자의 오른쪽 하단에 말합니다. 편집 텍스트를 확장하고 문자열을 수동으로 그리시겠습니까?
Bear

1
감사합니다 나도 그것을 얻었지만 텍스트를 입력하는 동안 150,149,148,147과 같은 역순으로 카운트 다운하는 방법.
vinay Maneti 2013

6
이 줄로 대체하여 해결되었습니다. mTextView.setText (String.valueOf (150-s.length ())); mTextView.setText (String.valueOf (s.length ()) 대신);
vinay Maneti 2013

내 문제는 @Bear와 비슷합니다. 편집 텍스트 바로 아래에이 카운트 다운 텍스트를 표시해야합니다. 누구든지이 참조에서 공유 할 것이 있습니다. 감사.
Suresh Sharma 2015 년

107

SupportLibrary v23.1에 도입 된 EditText 용 TextInputLayout 래퍼를 사용하여 xml 자체에서 문자 계산을 수행 할 수 있습니다.

EditText를 TextInputLayout으로 감싸고 CounterEnabled를 true로 설정하고 counterMaxLength를 설정하십시오.

<android.support.design.widget.TextInputLayout
    android:id="@+id/textContainer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:counterEnabled="true"
    app:counterMaxLength="20"
    >
    <EditText
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Text Hint"
        />
</android.support.design.widget.TextInputLayout>

당신은 같은 재료 효과를 얻을 것이다

counterOverflowTextAppearance , counterTextAppearance 를 사용 하여 카운터 스타일을 지정할 수 있습니다 .

편집하다

Android 문서에서.

TextInputEditText의 클래스는이 레이아웃의 자식으로 사용할 수 있도록 제공됩니다. TextInputEditText를 사용하면 TextInputLayout이 텍스트 입력의 시각적 측면을 더 잘 제어 할 수 있습니다. 사용 예는 다음과 같습니다.

     <android.support.design.widget.TextInputLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content">

     <android.support.design.widget.TextInputEditText
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:hint="@string/form_username"/>

 </android.support.design.widget.TextInputLayout>

TextInputLayout TextInputEditText


3
이것은 내가 찾던 바로 그 것이었다 :) 깨끗한 지원 라이브러리 impl. 감사합니다
VPZ 2015

3
수락 된 답변이어야합니다! 나는 그 속성을 완전히 놓쳤다!
sud007

24

다음 TextInputLayout과 같이 라이브러리와 호환 할 수 있습니다 .

app:counterEnabled="true"
app:counterMaxLength="420"

완료 :

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:counterEnabled="true"
    app:counterMaxLength="420">

    <EditText
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:maxLength="420" />

</android.support.design.widget.TextInputLayout>

이것은 나를 위해 일했지만 카운터의 색상을 어떻게 변경합니까?
Erich García

14

xml에서 editText에이 속성을 추가하십시오.

    android:maxLength="80"

자바 에서이 리스너 추가

  ed_caption.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) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            tv_counter.setText(80 - s.toString().length() + "/80");

        }
    });

7

매우 간단합니다. 아래 지침을 따르십시오.

==== 가져 오기에 추가 ===

import android.text.Editable;
import android.text.TextWatcher;

=====이 정의 =====

private TextView sms_count;

========== 만들기 내부 =====

sms_count = (TextView) findViewById(R.id.textView2);


final TextWatcher txwatcher = new TextWatcher() {
   public void beforeTextChanged(CharSequence s, int start, int count, int after) {
   }

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

      sms_count.setText(String.valueOf(s.length()));
   }

   public void afterTextChanged(Editable s) {
   }
};

sms_message.addTextChangedListener(txwatcher);

5
    You can use TextWatcher class to see text has changed and how much number of character remains.Here i have set counter of 140 characters.

    EditText typeMessageToPost;
    TextView number_of_character;
public void onCreate(Bundle savedBundleInstance) {
        super.onCreate(savedBundleInstance);
setContentView(R.layout.post_activity);
typeMessageToPost.addTextChangedListener(mTextEditorWatcher);
}
private final TextWatcher mTextEditorWatcher=new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            number_of_character.setText(String.valueOf(140-s.length()));
        }
    };

감사합니다 @RavishSharma :) 귀하의 의견에 감사드립니다.
Rana Pratap Singh

4

TextInputLayoutXML 파일에 다음 두 줄을 설정 하십시오.

app:counterEnabled="true"
app:counterMaxLength="200"

그레이트는 그것에 대해 몰랐습니다. Edittext를 TextInputLayout으로 래핑하는 것이 항상 더 나은 솔루션 인 것 같습니다.
Stefan Sprenger

3

이 솔루션은 Kotlin남은 문자 수를 사용 하고 표시합니다. 또한 현재 문자 수가 50 자 한도를 초과하면 텍스트 색상이 빨간색으로 변경됩니다.

Kotlin

private val mTitleTextWatcher = object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        if(YOUR_EDIT_TEXT_ID.text.toString().trim().length < 51){
            YOUR_CHAR_LEFT_TEXTVIEW_ID.text = (50 - YOUR_EDIT_TEXT_ID.text.toString().trim().length).toString()
            YOUR_CHAR_LEFT_TEXTVIEW_ID.setTextColor(Color.BLACK)
        }
        else{
            YOUR_CHAR_LEFT_TEXTVIEW_ID.text = "0"
            YOUR_CHAR_LEFT_TEXTVIEW_ID.setTextColor(Color.RED)
        }
    }

    override fun afterTextChanged(s: Editable) {}
}

또한에 추가하는 TextWatcher것을 잊지 마십시오.EditText

YOUR_EDIT_TEXT_ID.addTextChangedListener(mTitleTextWatcher)

3

TextInputLayout에 래핑되는 TextInputEditText에 카운터를 추가 할 수 있습니다. 예제에서 볼 counterEnabled수 있듯이이 기능을 활성화하고 counterMaxLengh문자 수를 정의합니다.

<com.google.android.material.textfield.TextInputLayout
        android:id="@+id/til_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:counterEnabled="true"
        app:counterMaxLength="50">
    <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/et_title"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
</com.google.android.material.textfield.TextInputLayout>

1

나는 같은 문제를 만났고 Cameron의 방법을 시도했습니다. 작동하지만 사소한 버그가 있습니다. 사용자가 복사하여 붙여 넣기를 사용하면 문자 수를 계산하지 못합니다. 따라서 다음과 같이 텍스트가 변경된 후에 수행하는 것이 좋습니다.

    private final TextWatcher mTextEditorWatcher = new TextWatcher() {
         public void beforeTextChanged(CharSequence s, int start, int count, int after) {

         }

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

         }

          public void afterTextChanged(Editable s) {
             //This sets a textview to the current length
             mTextView.setText(String.valueOf(s.length()));
         }
    };


0

이런 식으로 시도하십시오.

이 솔루션은 CharSequence.length를 얻는 것보다 성능이 더 우수 할 수 있습니다. 소프트 키보드를 탭할 때마다 이벤트가 발생합니다. 따라서 길이를 수행하면 매번 CharSequence를 계산하므로 큰 CharSequnce에 들어가기 시작하면 속도가 느려질 수 있습니다. 텍스트 변경시 이벤트 리스너는 이전 및 이후 카운트를 고정합니다. 이것은 증가 및 감소 값에 대해 잘 작동합니다.

@Override
        public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
            int tick = start + after;
            if(tick < mMessageMax) {
                int remaining = mMessageMax - tick;
                ((TextView)findViewById(R.id.contact_us_chars)).setText(String.valueOf(remaining));
            }
        }

이 TextWatcher이에 대한 최선의 방법입니다, 효과 permosrmatce입니다
Naveed 아마드

0

이 시도

private TextWatcher textWatcher = new TextWatcher() {
    @Override
    public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
        editText.post(new Runnable() {
            @Override
            public void run() {
                if (length < 100) {
                    if (count > 0 && after <= 0)/*remove emoij*/ {
                        length--;
                    } else if (count > after)/*remove text*/ {
                        length--;
                    } else if (count == 0 && after > 1)/*emoij*/ {
                        ++length;
                    } else if (count == 0 && after == 1)/*Text*/ {
                        ++length;
                    } else if (count > 0 && after > 1) {
                        ++length;
                    }
                    if (s.length() <= 0)
                        length = 0;
                    Log.w("MainActivity", " Length: " + length);
                } else {
                    if (count > 0 && after <= 0)/*remove emoij*/ {
                        length--;
                    } else if (count > after)/*remove text*/ {
                        length--;
                    }
                    Log.w("MainActivity", " Length: " + length);
                }

                if (length == 100) {
                    editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(s.length())});
                } else {
                    editText.setFilters(new InputFilter[]{});
                }
            }
        });
    }

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

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
};

`


0

명확한 방법;

abstract class CharacterWatcher : TextWatcher {
    override fun afterTextChanged(text: Editable?) {
        afterCharacterChanged(text?.lastOrNull(), text?.length)
    }

    override fun beforeTextChanged(text: CharSequence?, start: Int, count: Int, before: Int) {}

    override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) {}

    abstract fun afterCharacterChanged(char: Char?, count: Int?)
}



 editText.addTextChangedListener(new CharacterWatcher() {
            @Override
            public void afterCharacterChanged(@Nullable Character character, @Nullable Integer count) {
                action()
            }
        });
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.