如何用货币蒙版EditText构建ListView

时间:2019-06-13 17:07:54

标签: java android android-listview android-edittext

我正在开发一个应用程序,该应用程序需要一个带货币屏蔽的EditText的ListView和一个显示项目总和的摘要TextView。

我制作了一个自定义适配器。货币掩码(格式BRL R $ 0.000,00)正在运行。
当用户键入每个项目的EditText时如何使它们求和?

这是适配器的代码:

public AdapterFaturamentoMes(Context context, ArrayList<FaturamentoMes> lista) {
    this.context = context;
    this.lista = lista;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    FaturamentoMes item = lista.get(position);
    View view = convertView;

    if (view == null) {
        view = LayoutInflater.from(context).inflate(R.layout.layout_lista_faturamento_mes, parent, false);
    }

    TextView txtFaturamentoMes = view.findViewById(R.id.txtFaturamentoMes);
    EditText edFaturamento  = view.findViewById(R.id.edFaturamento);

    txtFaturamentoMes.setText(String.format(context.getString(R.string.txt_faturamento_mes), numberFormat.format(item.getMes()), numberFormat.format(item.getAno())));
    edFaturamento.setText(decimalFormat.format(item.getValor()));

    TextWatcher oldListener = (TextWatcher) edFaturamento.getTag();
    if (oldListener != null) edFaturamento.removeTextChangedListener(oldListener);

    TextWatcher watcher = new TextWatcher() {
        double valor;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!s.toString().equals(atual)) {
                edFaturamento.removeTextChangedListener(this);
                String texto = s.toString().replaceAll("[.,]", "");
                valor = Double.parseDouble("0" + texto);
                String valorFormatado = decimalFormat.format(valor/100);
                atual = valorFormatado;

                edFaturamento.setText(valorFormatado);
                edFaturamento.setSelection(valorFormatado.length());
                edFaturamento.addTextChangedListener(this);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    edFaturamento.setTag(watcher);
    edFaturamento.addTextChangedListener(watcher);

    return view;
}

public ArrayList<FaturamentoMes> getLista() {
    return lista;
}

@Override
public int getCount() {
    return this.lista.size();
}

@Nullable
@Override
public FaturamentoMes getItem(int position) {
    return this.lista.get(position);
}

@Override
public long getItemId(int position) {
    return 0;
} 
}

0 个答案:

没有答案