Số lượng ký tự trực tiếp cho EditText


101

Tôi đã tự hỏi cách tốt nhất để thực hiện đếm ký tự trực tiếp của một hộp văn bản chỉnh sửa là gì trong Android. Tôi đang nhìn cái này nhưng dường như tôi không thể hiểu được nó.

Để mô tả vấn đề, tôi có một EditText và tôi đang cố gắng giới hạn số ký tự ở 150. Tôi có thể thực hiện việc này bằng bộ lọc đầu vào, tuy nhiên tôi muốn hiển thị ngay bên dưới hộp văn bản số ký tự mà người dùng đã nhập (Hầu như như tràn ngăn xếp đang làm ngay bây giờ).

Nếu ai đó có thể viết một đoạn mã ví dụ nhỏ hoặc chỉ cho tôi đi đúng hướng, tôi sẽ đánh giá rất cao.

Câu trả lời:


153

bạn có thể sử dụng TextWatcher để xem khi nào văn bản đã thay đổi

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) {
        }
};

bạn đặt TextWatcher cho văn bản chỉnh sửa với

mEditText.addTextChangedListener(mTextEditorWatcher);

5
đã thử điều này, hoạt động tuyệt vời! nên được chọn là câu trả lời đúng!
Patrick Boos

2
cách tốt nhất để thêm số nói ở dưới cùng bên phải của hộp văn bản. Mở rộng văn bản chỉnh sửa và vẽ chuỗi theo cách thủ công?
Chịu

1
Cảm ơn tôi cũng hiểu, nhưng làm thế nào để đếm ngược theo thứ tự ngược lại như 150,149,148,147 .... trong khi nhập văn bản.
vinay Maneti

6
Nó được giải quyết bằng cách thay thế bằng dòng này mTextView.setText (String.valueOf (150-s.length ())); thay cho mTextView.setText (String.valueOf (s.length ()));
vinay Maneti

Vấn đề của tôi cũng tương tự như @Bear have. Tôi cần hiển thị văn bản đếm ngược này ngay bên dưới văn bản chỉnh sửa. Bất kỳ ai có bất cứ điều gì để chia sẻ trong tài liệu tham khảo này. Cảm ơn.
Suresh Sharma

107

Bạn có thể thực hiện đếm ký tự từ chính xml bằng cách sử dụng trình bao bọc TextInputLayout cho EditText được giới thiệu trong SupportLibrary v23.1

Chỉ cần bọc EditText của bạn bằng một TextInputLayout và đặt CounterEnabled thành true và Đặt 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>

Bạn sẽ nhận được hiệu ứng vật chất như thế này

Bạn có thể sử dụng counterOverflowTextAppearance , counterTextAppearance để tạo kiểu cho bộ đếm.

BIÊN TẬP

Từ tài liệu Android.

Lớp TextInputEditText được cung cấp để sử dụng như một phần tử con của bố cục này. Sử dụng TextInputEditText cho phép TextInputLayout kiểm soát tốt hơn các khía cạnh trực quan của bất kỳ đầu vào văn bản nào. Một ví dụ sử dụng là như vậy:

     <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
đây chính xác là những gì tôi đang tìm kiếm :) một thư viện hỗ trợ sạch sẽ. cảm ơn
VPZ

3
Nên là câu trả lời được Chấp nhận! Tôi hoàn toàn bỏ lỡ những thuộc tính đó!
sud007

24

Bạn có thể làm điều đó với TextInputLayoutvà so sánh các thư viện với:

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

và hoàn thành:

<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>

Điều này tuyệt vời làm việc cho tôi, nhưng làm thế nào tôi thay đổi màu của bộ đếm?
Erich García

14

trong xml thêm thuộc tính này cho editText

    android:maxLength="80"

trong java thêm trình nghe này

  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

Nó rất đơn giản Làm theo hướng dẫn bên dưới:

==== Thêm chúng vào Nhập của bạn ===

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

===== Xác định điều này =====

private TextView sms_count;

========== Inside On Create =====

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()));
        }
    };

Cảm ơn @RavishSharma :) Tôi đánh giá cao nhận xét của bạn.
Rana Pratap Singh

4

Chỉ cần đặt 2 dòng này trong TextInputLayouttệp XML của bạn:

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

Tuyệt không biết về điều đó. Có vẻ như luôn luôn là giải pháp tốt hơn để bọc một Edittext vào một TextInputLayout.
Stefan Sprenger

3

Giải pháp này sử dụng Kotlinvà hiển thị số ký tự còn lại. Ngoài ra, nếu số ký tự hiện tại vượt qua giới hạn 50, màu văn bản sẽ chuyển thành màu đỏ.

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) {}
}

Ngoài ra, đừng quên thêm TextWatchervàoEditText

YOUR_EDIT_TEXT_ID.addTextChangedListener(mTitleTextWatcher)

3

Bạn có thể thêm bộ đếm vào TextInputEditText của bạn đang được bao bọc trong TextInputLayout. Như bạn có thể thấy trong ví dụ, hãy counterEnabledbật tính năng này và counterMaxLenghxác định số ký tự cho nó.

<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

Tôi đã gặp vấn đề tương tự và tôi đã thử phương pháp của Cameron. Nó hoạt động nhưng có một lỗi nhỏ: Nếu người dùng sử dụng sao chép và dán thì nó không thể đếm các ký tự. Vì vậy, tôi đề nghị làm sau khi văn bản thay đổi, như dưới đây:

    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

Hãy thử làm điều gì đó như thế này.

Giải pháp này có thể hiệu quả hơn thay vì lấy CharSequence.length. Mỗi lần bạn gõ vào bàn phím mềm, sự kiện sẽ kích hoạt; do đó, nếu bạn thực hiện một độ dài, nó sẽ tính CharSequence mỗi lần, điều này có thể chậm lại nếu bạn bắt đầu vào CharSequnces lớn. Trình nghe sự kiện trên thay đổi văn bản sẽ đếm trước và sau. Điều này hoạt động tốt cho các giá trị tăng và giảm

@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));
            }
        }

đây là hiệu ứng permosrmatce, TextWatcher là cách tiếp cận tốt nhất cho điều này
Naveed Ahmad

0

thử cái này

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

Đường đi rõ ràng;

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()
            }
        });
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.