How to get multiple variables from one EditText?

2019-08-31 14:49发布

问题:

I'm looking for a way to get three float values from one EditText.I've Looked of the developers page but i couldnt find anything that best fit my need.I would like to get three floats a x,y,z from one entry of EditText?

Thank you guys so much on the replys o this Question im really greatfull. Im limited to the time on my computer right now but ill let you know which answer work for me and ill post my code too.

回答1:

String value = yourEditText.getText().toString();
String[] floatStrings = value.split(",");
float[] result = new float[floatString.length];
for (int i=0; i<result.length; i++) {
    result[i] = Float.valueOf(floatStrings[i];
}

?



回答2:

If they are separated by whitespaces

Scanner sc = new Scanner(yourEditText.getText().toString());

float vals = new float[3];

while(int i=0; sc.hasNextFloat() && (i < 3); ++i) {
   vals[i] = sc.nextFloat();
}

otherwise use Scanner.setDelimiter to set delimiter(s) other than whitespaces.

Reconsider your design to use three EditTexts instead. On mobile phones it's a pain to enter symbols like comma



回答3:

Use 3 EditText widgets if you want the user to input 3 separate values, which will be parsed as 3 separate variables.



回答4:

You should either create several EditText views, or then parse the contents of the EditText

EditText textView;

String[] splitFloatStrings = textView.getText().toString();.split(",");
float[] parsedFloats = new float[splitFloatStrings.length];

for (int i=0; i < parsedFloats.length; i++) {
    parsedFloats[i] = Float.valueOf(splitFloatStrings[i];
}

As per Java parsing a string of floats to a float array?