I'm needing to get an integer from the user for one of my apps and I have tried using a text edit but it didn't seem to work, so I'm wanting to know another way of getting an integer from the user. The int will be positive numbers only and no more than 2 digits.
Asked
Active
Viewed 72 times
3 Answers
0
You have to use EditText.. then from in Your Activity
String s = ed.getText().ToString();
int i = 0;
if(s!=null)
i= Integer.valueOf(s);
To make sure keyboard only show numbers, make sure you add
android:input="number"
to your EditText in the XML
UPDATE
yourEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
String s = yourEditText.getText().ToString();
int i = 0;
if(s!=null)
i= Integer.valueOf(s);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});

Mo Adel
- 1,136
- 1
- 16
- 29
-
This is what I was using and it wouldn't work. Where would I put this code since it needs to run every time the edittext is edited. – MDubzem Jun 29 '14 at 02:09
-
You have to create a button and set and OnClickListener on it so when the user finish he can click on the button. Inside the onClickListener you can out the above code – Mo Adel Jun 29 '14 at 02:26
-
or you can have an OnChangeLisener and still put the above code inside it http://stackoverflow.com/a/11134227/2040750 – Mo Adel Jun 29 '14 at 02:28
-
So I might as well use an alert dialog – MDubzem Jun 29 '14 at 02:29
-
If you mean an AlertDialog with EditText yes definitely you can – Mo Adel Jun 29 '14 at 02:31
0
Use EditText
You can limit the number of digits like this
Update: Then you need to add a listener
a relevant question:

Community
- 1
- 1

yildirimyigit
- 3,013
- 4
- 25
- 35
-
yes that's what I was doing but I would prefer a different way so that it updates the int when the user edits the text – MDubzem Jun 29 '14 at 02:13
0
you can use properties in your XML .
use this line to limit input text in numbers in XML :
android:inputType="number"
and use this line to set your specific character:
android:digits="1234567890"
i think it is the best way for this purpose.

Mohammad
- 1,197
- 2
- 13
- 30