Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Libgdx native TextInput limit text Length

I am writing a game using Libgdx. I used what was suggested here to handle virtual keyboard when user enters player names. This actually works like a charm. However if user enters more than 8 characters in a name field, it breaks the UI design of my game. So I want to prevent user from entering more than 8 characters.

TextField has a setMaxLength method as defined here. If I set this value to 8, no matter what user enters, the first 8 characters are put in my text field. But this is kind of annoying and misleading because user can still enter, let's say 20 characters without having a clue that the only first 8 will be used.

So, my question is whether there is a mechanism to stop user entering more than 8 characters even if I use "native" way of handling TextField inputs.

Thanks in advance.

like image 635
Alp Avatar asked Apr 25 '26 08:04

Alp


1 Answers

I tested this just before typing to you, so I know it works. The below code will make it so your textfield will only allow for you to enter in 8 characters into the TextField widget. Be careful though, some characters are larger (in length) than others ( chars like - are short ).

textField.setMaxLength(8);  // Maximum chars will be 8
textField.setAlignment(1);  // If you wanted to center the text
                            //     (1 = Center, 2 = Right Align)

On another note, if you are adding the TextField to a table, you can change the visible width of the widget.

table.add(textField).width(50);  // I believe this is in pixels

You didn't really give me much to go off from (no code), so I hope this answer helps you out.

Best of luck with your game!


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!