如何从EditText中获取值并将它们加到数组中

时间:2014-01-31 14:50:55

标签: android arrays

我有两个Edit-text例如。我想取用户输入的值。并在array上总结它们。

请说出这样的代码。

EditText oneValue = (EditText)addView.findViewById(R.id.one);
EditText twoValue = (EditText)addView.findViewById(R.id.two);

如果用户在5中输入了oneValue,在7中输入了twoValue。我如何在数组中加总它们?

3 个答案:

答案 0 :(得分:0)

假设你想要一个字符串列表:

List<String> array = new ArrayList<String>();
array.add(oneValue.getText().toString());
array.add(twoValue.getText().toString());

如果您需要String []:

String[] array = new String[2];
array[0] = oneValue.getText().toString();
array[1] = twoValue.getText().toString();

如果您需要整数:

Integer[] array = new Integer[2];
try {

    array[0] = Integer.parseInt(oneValue.getText().toString());
    array[1] = Integer.parseInt(twoValue.getText().toString());
} catch (NumberFormatException e){
    // handle number parsing exception (the content of the EditText is not a valid number)
}

如果您需要数组中的实际5+7字符串:

List<String> array = new ArrayList<String>();
array.add(oneValue.getText().toString()+ " + " + twoValue.getText().toString());

如果需要将5 + 7的结果添加到整数数组:

List<Integer> array = new ArrayList<Integer>();
array.add(Integer.parseInt(oneValue.getText().toString()) + Integer.parseInt(twoValue.getText().toString()));

答案 1 :(得分:0)

关于数组的使用,我的问题并不完全清楚。如果要在两个编辑文本中添加值,请遵循以下步骤。

int val1 = Integer.valueOf(oneValue.getText().toString());
int val2 = Integer.valueOf(twoValue.getText().toString());
int sum = val1 + val2;

这是你可以对EditText s中的值求和的方法。我不清楚数组部分。

以下代码将返回(文本)值的字符串数组。

String[] values = new String[]{oneValue.getText().toString(), twoValue.getText().toString()};
return values;

答案 2 :(得分:0)

你是什么意思“将它们排成一列”? 如果要添加2个值并在数组中添加求和值,则可以执行以下操作:

int[] array = new int[10]; // Any size

int a = Integer.parseInt(oneValue.getText().toString());

int b = Integer.parseInt(twoValue.getText().toString());

int c = a + b;

array[0] = c; // Any position
相关问题