I'm creating an app to calculate an arithmetic mean of N values. There is an add button, when it is clicked it will generate EditText
programmatically. And it will have a calculate button, when it is clicked, it should show the average of the EditText
created.
But I'm not able to retrieve the values of these EditText
to use on the calculate button. Below is my java code:
private ArrayList<EditText> listEdit = new ArrayList<>();
botaoAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
aviso.setVisibility(View.GONE);
LinearLayout layout = (LinearLayout) view.findViewById(R.id.container); //criar o container(pai)
listEdit.add(new EditText(getActivity()));
listEdit.get(count).setBackgroundColor(Color.WHITE);
listEdit.get(count).setHint("Media " + count);
listEdit.get(count).setGravity(Gravity.CENTER);
listEdit.get(count).setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
layout.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(300,100); // tamanho do container
layoutParams.setMargins(0,15,0,0);
layout.addView(listEdit.get(count),layoutParams); //adicionando a view ao container
count++;
}
});
botaoCalc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (int i =0; i < listEdit.size(); i++){
String texto = listEdit.get(i).getText().toString();
if(!texto.isEmpty()){
Double valor = Double.parseDouble(texto);
Double result = 0.0;
result = result + valor;
Double media = result/(i+1);
resultado.setText("media " + media);
}
}
}
});
As I've read in other posts here, they have always recommended that you save the values of EditText
to ArrayList
to use it. The problem with this code is that it is not adding the values, it is only taking the value of the last EditText
and dividing by the number of EditText
s (in this case, i
of for
). >