Android實戰(二)—— 房貸計算器

知識點:
下拉框Spinner的學習。

public class MainActivity extends AppCompatActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener, CompoundButton.OnCheckedChangeListener {
......
        initYearSpinner();
        initRatioSpinner();
    }

    // 初始化貸款年限
    private void initYearSpinner() {
        ArrayAdapter<String> yearAdapter = new ArrayAdapter<>(this, R.layout.item_select, yearDescArray);
        yearAdapter.setDropDownViewResource(R.layout.item_dropdown);
        Spinner sp_year = findViewById(R.id.sp_year);
        sp_year.setPrompt("請選擇貸款年限");
        sp_year.setAdapter(yearAdapter);
        sp_year.setSelection(0);
        sp_year.setOnItemSelectedListener(new YearSelectedListener());
    }

    private String[] yearDescArray = {"5年", "10年", "15年", "20年", "30年"};
    private int[] yearArray = {5, 10, 15, 20, 30};

    // 初始化基準利率下拉框
    private void initRatioSpinner(){
        ArrayAdapter<String> ratioAdapter = new ArrayAdapter<>(this, R.layout.item_select, ratioDescArray);
        ratioAdapter.setDropDownViewResource(R.layout.item_dropdown);
        Spinner sp_radio = findViewById(R.id.sp_ratio);
        sp_radio.setPrompt("請選擇基準利率");
        sp_radio.setAdapter(ratioAdapter);
        sp_radio.setSelection(0);
        sp_radio.setOnItemSelectedListener(new RatioSelectedListener());
    }
    private String[] ratioDescArray = {
            "2015年10月24日 五年期商貸利率 4.90% 公積金利率 3.25%",
            "2015年08月26日 五年期商貸利率 5.15% 公積金利率 3.25%",
            "2015年06月28日 五年期商貸利率 5.40% 公積金利率 3.50%",
            "2015年05月11日 五年期商貸利率 5.65% 公積金利率 3.75%",
            "2015年03月01日 五年期商貸利率 5.90% 公積金利率 4.00%",
            "2014年11月22日 五年期商貸利率 6.15% 公積金利率 4.25%",
            "2012年07月06日 五年期商貸利率 6.55% 公積金利率 4.50%",
    };
    private double[] businessArray = {4.90, 5.15, 5.40, 5.65, 5.90, 6.15, 6.55};
    private double[] accumulationArray = {3.25, 3.25, 3.50, 3.75, 4.00, 4.25, 4.50};


    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_loan){
            if (TextUtils.isEmpty(et_price.getText().toString())){
                Toast.makeText(this, "購房總價不能爲空", Toast.LENGTH_SHORT).show();
                return;
            }
            if(TextUtils.isEmpty(et_loan.getText().toString())){
                Toast.makeText(this, "按揭部分不能爲空", Toast.LENGTH_SHORT).show();
                return;
            }
            showLoan();     // 顯示i計算好的貸款總額
        }else if(v.getId() == R.id.btn_calculate){
            if(hasBusiness && TextUtils.isEmpty(et_business.getText().toString())){
                Toast.makeText(this, "商業貸款總額不能爲空", Toast.LENGTH_SHORT).show();
                return;
            }
            if(hasAccumulation && TextUtils.isEmpty(et_accumulation.getText().toString())){
                Toast.makeText(this, "公積金貸款總額不能爲空", Toast.LENGTH_SHORT).show();
                return;
            }
            if(!hasBusiness && !hasAccumulation){
                Toast.makeText(this, "請選擇商業貸款或公積金貸款", Toast.LENGTH_SHORT).show();
                return;
            }
            showRepayment();    // 顯示計算好的還款明細
        }
    }

    // 根據購房總價和按揭比例,計算貸款總額
    private void showLoan(){
        double total = Double.parseDouble(et_price.getText().toString());
        double rate = Double.parseDouble(et_loan.getText().toString()) / 100;
        String desc = String.format("您的貸款總額爲%s萬元", formatDecimal(total * rate, 2));
        tv_loan.setText(desc);
    }

    // 根據貸款的相關條件,計算還款總額、利息總額,以及月供
    private void showRepayment() {
        Repayment businessResult = new Repayment();
        Repayment accumulationResult = new Repayment();
        if (hasBusiness) { // 申請了商業貸款
            double businessLoad = Double.parseDouble(et_business.getText().toString()) * 10000;
            double businessTime = mYear * 12;
            double businessRate = mBusinessRatio / 100;
            // 計算商業貸款部分的還款明細
            businessResult = calMortgage(businessLoad, businessTime, businessRate, isInterest);
        }
        if (hasAccumulation) { // 申請了公積金貸款
            double accumulationLoad = Double.parseDouble(et_accumulation.getText().toString()) * 10000;
            double accumulationTime = mYear * 12;
            double accumulationRate = mAccumulationRatio / 100;
            // 計算公積金貸款部分的還款明細
            accumulationResult = calMortgage(accumulationLoad, accumulationTime, accumulationRate, isInterest);
        }
        String desc = String.format("您的貸款總額爲%s萬元", formatDecimal(
                (businessResult.mTotal + accumulationResult.mTotal) / 10000, 2));
        desc = String.format("%s\n  還款總額爲%s萬元", desc, formatDecimal(
                (businessResult.mTotal + businessResult.mTotalInterest +
                        accumulationResult.mTotal + accumulationResult.mTotalInterest) / 10000, 2));
        desc = String.format("%s\n其中利息總額爲%s萬元", desc, formatDecimal(
                (businessResult.mTotalInterest + accumulationResult.mTotalInterest) / 10000, 2));
        desc = String.format("%s\n  還款總時間爲%d月", desc, mYear * 12);
        if (isInterest) { // 如果是等額本息方式
            desc = String.format("%s\n每月還款金額爲%s元", desc, formatDecimal(
                    businessResult.mMonthRepayment + accumulationResult.mMonthRepayment, 2));
        } else { // 如果是等額本金方式
            desc = String.format("%s\n首月還款金額爲%s元,其後每月遞減%s元", desc, formatDecimal(
                    businessResult.mMonthRepayment + accumulationResult.mMonthRepayment, 2),
                    formatDecimal(businessResult.mMonthMinus + accumulationResult.mMonthMinus, 2));
        }
        tv_payment.setText(desc);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.rb_interest) { // 選擇了等額本息方式
            isInterest = true;
        } else if (checkedId == R.id.rb_principal) { // 選擇了等額本金方式
            isInterest = false;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView.getId() == R.id.ck_business) { // 勾選了商業貸款
            hasBusiness = isChecked;
        } else if (buttonView.getId() == R.id.ck_accumulation) { // 勾選了公積金貸款
            hasAccumulation = isChecked;
        }
    }

    // 精確到小數點後第幾位
    private String formatDecimal(double value, int digit) {
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(digit, RoundingMode.HALF_UP);
        return bd.toString();
    }

    // 根據貸款金額、還款年限、基準利率,計算還款信息
    private Repayment calMortgage(double ze, double nx, double rate, boolean bInterest) {
        double zem = (ze * rate / 12 * Math.pow((1 + rate / 12), nx))
                / (Math.pow((1 + rate / 12), nx) - 1);
        double amount = zem * nx;
        double rateAmount = amount - ze;

        double benjinm = ze / nx;
        double lixim = ze * (rate / 12);
        double diff = benjinm * (rate / 12);
        double huankuanm = benjinm + lixim;
        double zuihoukuan = diff + benjinm;
        double av = (huankuanm + zuihoukuan) / 2;
        double zong = av * nx;
        double zongli = zong - ze;

        Repayment result = new Repayment();
        result.mTotal = ze;
        if (bInterest) {
            result.mMonthRepayment = zem;
            result.mTotalInterest = rateAmount;
        } else {
            result.mMonthRepayment = huankuanm;
            result.mMonthMinus = diff;
            result.mTotalInterest = zongli;
        }
        return result;
    }

    private class YearSelectedListener implements AdapterView.OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            mYear = yearArray[position];
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {}
    }

    private class RatioSelectedListener implements AdapterView.OnItemSelectedListener {
        @Override
        public void onNothingSelected(AdapterView<?> parent) {}

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            mBusinessRatio = businessArray[position];
            mAccumulationRatio = accumulationArray[position];
        }
    }
}

運行效果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章