我正在尝试在警告对话框中验证一些EditTexts,但是当我点击“确定”按钮时,警报就会解除,因为您可以在我的代码中看到我有一条错误消息,如果该字段是空的,我在这里缺少什么,任何帮助都将不胜感激。
final TextView id = (TextView) spinner.getSelectedView();
final EditText descricao = (EditText) v.findViewById(R.id.add_descricao);
final EditText observacao = (EditText) v.findViewById(R.id.add_observacao);
final EditText data = (EditText) v.findViewById(R.id.add_data);
final EditText valor = (EditText) v.findViewById(R.id.add_valor);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
data.setError(null);
valor.setError(null);
String campo_data = data.getText().toString();
String campo_valor = valor.getText().toString();
if (TextUtils.isEmpty(campo_data)) {
data.setError(getString(R.string.flObrigatorio));
focusView = data;
op = true;
}
if (TextUtils.isEmpty(campo_valor)) {
valor.setError(getString(R.string.flObrigatorio));
focusView = data;
op = true;
}
if (op) {
focusView.requestFocus();
} else {
DespesaModel mDespesaModel = new DespesaModel();
//Formata data para enviar para o banco
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Repositorio mRepositorio = new Repositorio(getApplicationContext());
DespesaCategoriaModel mDespesaCategoriaModel = mRepositorio.getCategoriaDespesaPorId(id.getId(), false);
mDespesaModel.setId_rm_empresa(Integer.valueOf(rm_IdEmpresa));
mDespesaModel.setId_rm_despesa_categoria(mDespesaCategoriaModel.getId_rm());
mDespesaModel.setId_despesa_categoria(mDespesaCategoriaModel.getId());
mDespesaModel.setId_rm_credencial(Integer.valueOf(mSessao.getString("id_credencial")));
mDespesaModel.setId_rm_viagem(Integer.valueOf(rm_IdViagem));
mDespesaModel.setData(mFerramentas.dataBr(campo_data));
mDespesaModel.setValor(valor.getText().toString().substring(2).replace(".", "").replace(",", "."));
mDespesaModel.setDescricao(descricao.getText().toString());
mDespesaModel.setObservacao(observacao.getText().toString());
mDespesaModel.setCriado(ft.format(dNow));
mDespesaModel.setModificado(ft.format(dNow));
mDespesaModel.setStatus("A");
mRepositorio.CadastrarDespesa(mDespesaModel, false);
carregaDespesas();
}
}
});
答案 0 :(得分:13)
您没有告诉应用程序它应该保留在AlertDialog
上,您只是为对象设置错误。
解决方案是将onShowListener
事件添加到AlertDialog
,您可以在其中覆盖按钮的onClickListener
。
示例:
final AlertDialog d = new AlertDialog.Builder(context)
.setView(v)
.setTitle(R.string.my_title)
.setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
.setNegativeButton(android.R.string.cancel, null)
.create();
d.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO Do something
//Dismiss once everything is OK.
d.dismiss();
}
});
}
});