有没有办法预定义字符串的值,以便在任何字段为空时不会出现错误? 所有porcentagem 1,2和3都是可选的,因此不是要求用户输入一些数据,而是预定义值以便不具有值。初学者问题。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cpc_inicial = (EditText) findViewById(R.id.cpc_inicial);
porcentagem1 = (EditText) findViewById(R.id.porcentagem1);
porcentagem2 = (EditText) findViewById(R.id.porcentagem2);
porcentagem3 = (EditText) findViewById(R.id.porcentagem3);
cpc_final = (TextView) findViewById(R.id.cpc_final);
botao1 = (Button) findViewById(R.id.botao1);
cpc_inicial.setInputType(InputType.TYPE_CLASS_NUMBER);
porcentagem1.setInputType(InputType.TYPE_CLASS_NUMBER);
porcentagem2.setInputType(InputType.TYPE_CLASS_NUMBER);
porcentagem3.setInputType(InputType.TYPE_CLASS_NUMBER);
botao1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(porcentagem3 != null ) {
float cpc = Float.parseFloat(cpc_inicial.getText().toString());
float v1 = Float.parseFloat(porcentagem1.getText().toString());
float v2 = Float.parseFloat(porcentagem2.getText().toString());
float v3 = Float.parseFloat(porcentagem3.getText().toString());
TextView cpcfinal = cpc_final;
if(cpc > 0.0 && v1 != 0.0 && v2 != 0.0 && v3 != 0.0 )
{
soma = (cpc*v1/100)+cpc;
soma = soma*(v2/100)+soma;
soma = soma*(v3/100)+soma;
String sum = Float.toString(soma);
cpcfinal.setText(sum);
}
} else
{
TextView cpcfinal = cpc_final;
soma = 0;
cpcfinal.setText("ops!"); }
}
});
}
由于
答案 0 :(得分:2)
每次提交表单时,都应检查每个字段是否具有正确的值。例如,如果要检查天气,可选字段是否具有值,则应执行以下操作:
String optionalText = optionalFieldName.getText().toString();
if (optionalText.equals("some expected value")) {
//Do something with the value here.
}
当然,您需要为每个可选字段执行类似的操作,并且实际上也应该对不安全的选项执行反向操作,并且可能警告用户该字段是必需的,例如:< / p>
String text = fieldName.getText().toString();
if (text.equals("")) {
//field is empty, so warn the user that it is required.
}
如果您要查找的值本质上应为数值,那么您应该执行以下操作:
String text = field.getText().toString();
if (!text.equals("")) {
//Field has at least some text in it.
try {
float val = Float.parseFloat(text);
}catch (NumberFormatException ex) {
//Enterered text was not a float value, so you should do something
// here to let the user know that their input was invalid and what you expect
}
//Do something with the value
}
答案 1 :(得分:1)
使用android:text="..."
属性将值添加到xml布局中,或使用TextUtils.isEmpty(...)
检测字符串是否为空并自行分配默认值。