답변:
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);
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과 같이 라이브러리와 호환 할 수 있습니다 .
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>
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");
}
});
매우 간단합니다. 아래 지침을 따르십시오.
==== 가져 오기에 추가 ===
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);
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()));
}
};
TextInputLayoutXML 파일에 다음 두 줄을 설정 하십시오.
app:counterEnabled="true"
app:counterMaxLength="200"
이 솔루션은 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)
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>
나는 같은 문제를 만났고 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()));
}
};
android : maxLength = "140"사용
작동합니다. :)
도움이되는 희망
이런 식으로 시도하십시오.
이 솔루션은 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));
}
}
이 시도
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) {
}
};
`
명확한 방법;
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()
}
});