计算android中edittext的百分比值

时间:2015-05-26 04:00:13

标签: android android-edittext

我有代码添加多个edittext字段的值,并在一个字段中显示总数。现在我需要包括另外两个edittext字段的百分比计算以及总值。

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 + "");

    }
};

现在我需要计算服务税率(每月租金价值*服务税值)/ 100,并将此计算为总计。罚款百分比与服务税相同。服务税和罚款是另外两个edittext字段,月租金已包含在上述代码中。我怎么能得到这个?

1 个答案:

答案 0 :(得分:1)

假设service_tax_etpenalty_et是新editTexts,请不要将它们添加到数组中,而是手动设置focusChangeListener,然后尝试这样:

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 + "");
}};