In Android development, textwatcher monitoring is added to EditText control to limit the number of input words (recommended)

This function is done because when developing a project, the length of some parameters of the background interface is required to be no more than how many characters, so the characters entered in the edit box should be limited.

Let's take a look at the implementation process of the demo:

First, place an EditText control in the XML control, then initialize the control and add text listening to the control. XML has its own simple design. The code is relatively simple. You can directly use the code:

In the above code, when adding text listening to the EditText control, I use the custom textwatcher. There are three parameters that need to be passed. The methods are:

One is EditText control, that is, the edit box control to add listening;

One is the limited number of characters, that is, the content that can be entered in the edit box at most;

One is the context object of the current class.

Of course, if you want to add another textview control to display the number of input characters in real time, just pass another parameter. In any case, the specific needs and specific implementation are OK. There is little change. I learn to be flexible.

The most critical class, the custom textwatcher class, has the following code:

The above code has given comments and is very clear. Let's talk about my ideas!

First, this custom class needs to implement the textwatcher interface and override the related methods.

At this time, you need to know the number of characters in the edit box before the content is entered, the position of the cursor when the content is entered, and the number of characters in the edit box after the content is entered. After knowing this, it's simple. You know the maximum limit; At this time, you only need to delete the excess characters according to some of the above data. The specific implementation method is written in

There are key notes in the rewriting method. You can study it carefully. Maybe there will be a simpler method.

The above is what Xiaobian introduced to you. In Android development, textwatcher monitoring is added to EditText control to limit the number of input words (recommended). I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>