0

フィールドのいずれかが空の場合にエラーが発生しないように、文字列の値を事前定義する方法はありますか? 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!"); }
        }
    });
}

ありがとう

4

2 に答える 2

2

フォームが送信されるたびに、各フィールドの値が適切かどうかを確認する必要があります。たとえば、オプションのフィールドに値があるかどうかを天気を確認したい場合は、次のようにする必要があります。

String optionalText = optionalFieldName.getText().toString();
if (optionalText.equals("some expected value")) {
    //Do something with the value here.
}

もちろん、オプションのフィールドごとに同様のことを行う必要があり、オプションではないフィールドについては逆のことを安全に行う必要があり、おそらくフィールドが必須であることをユーザーに警告する必要があります。

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
} 
于 2013-02-24T00:35:09.803 に答える
1

android:text="..."属性を使用して xml レイアウトに値を追加TextUtils.isEmpty(...)するか、文字列が空かどうかを検出してデフォルト値を自分で割り当てるために使用します。

于 2013-02-24T00:32:08.160 に答える