Calculating percentages value of edittext in andro

2019-09-21 08:21发布

问题:

I have got the code to add the values of multiple edittext fields and display the total in one field. Now I need to include the percentage calculation of two more edittext fields along with the total value.

editTexts = new EditText[] {monthly_rent_et, water_et,eb_et,sewage_et,maint_et,others_et,sec_deposit_et};
    for (int i=0 ; i<editTexts.length ; i++) {
        editTexts[i].setOnFocusChangeListener(mFocusChangeListener);
    }

private View.OnFocusChangeListener mFocusChangeListener = new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int total = 0;
        for (int i=0 ; i<editTexts.length-1 ; i++) {

            try {
                total += Integer.valueOf(editTexts[i].getText().toString());
            }
            catch(Exception e) {}
        }
        total_et.setText(total + "");

    }
};

Now I need to calculate the service tax percentage (monthly rent value*service tax value)/100 and and this to total. Also penalty percentage as same like service tax. Service tax and penalty are two more edittext fields and the monthly rent is already included in the above code. How can I get this?

回答1:

Suppose service_tax_et and penalty_et are new editTexts, don't add them to the array instead set focusChangeListener on them manually and then try like this:

private View.OnFocusChangeListener mFocusChangeListener = new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
    float total = 0;
    for (int i=0 ; i<editTexts.length-1 ; i++) {
        try {
            total += Integer.valueOf(editTexts[i].getText().toString());
        }
        catch(Exception e) {}
    }

    try {
        float service_tax_perc = (Integer.valueOf(monthly_rent_et.getText().toString()) + Integer.valueOf(service_tax_et.getText().toString())) / 100;
        total += service_tax_perc;
    } catch (Exception e) {}

    try {
        float penalty_perc = (Integer.valueOf(monthly_rent_et.getText().toString()) + Integer.valueOf(penalty_et.getText().toString())) / 100;
        total += penalty_perc;
    } catch (Exception e) {}

    total_et.setText(total + "");
}};