0
I am creating an app pqra calculate an arithmetic mean of N values. There is a button add, when clicked it will generate a EditText
programmatically. And it will have a calculate button, when it is clicked, it should show the average of EditText
maids.
But I’m not getting back 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 read in other posts here, have always recommended keeping the values of EditText
in a ArrayList
to use it. The problem with this code is that it’s not adding up the values, it’s just taking the value of the last EditText
and divided by the number of EditText
s (in this case, the i
of for
).
Ahhh, I changed so much, I used chieldCont, and I didn’t notice that detail. It worked here, vlw :D
– Italo Oliveira
The only detail is that in this case use
double
(the primitive type) instead ofDouble
(the packaging class) is more efficient because it avoids unnecessary autoboxes and autounboxes.– Victor Stafusa