Android 理财计算器

1,549 阅读4分钟

Android 理财计算器

本文原创,转载请注明出处。欢迎关注我的 简书

前言:

最近因工作需要,自己撸了一个计算器Dialog,这边拿出来跟大家分享下,写的不好,请多指教
PS:知识点来不及写了,注释也没时间加,大家先看着,后续有时间再补上

先看效果图:


自己做的第一个GIF

Style:

    <style name="MyDialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowFrame">@null</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowFullscreen">true</item>
    </style>

    <style name="dialogWindowAnim" mce_bogus="1" parent="android:Animation">
        <item name="android:windowEnterAnimation">@anim/push_left_in</item>
        <item name="android:windowExitAnimation">@anim/push_left_out</item>
    </style>

Keyboard.xml:

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@color/white"
    android:keyHeight="10%p"
    android:keyWidth="100%p" >

    <Row>
        <Key
            android:codes="55"
            android:keyEdgeFlags="left"
            android:keyLabel="7" />
        <Key
            android:codes="56"
            android:keyLabel="8" />
        <Key
            android:codes="57"
            android:keyLabel="9" />
    </Row>
    <Row>
        <Key
            android:codes="52"
            android:keyEdgeFlags="left"
            android:keyLabel="4" />
        <Key
            android:codes="53"
            android:keyLabel="5" />
        <Key
            android:codes="54"
            android:keyLabel="6" />
    </Row>
    <Row>
        <Key
            android:codes="49"
            android:keyEdgeFlags="left"
            android:keyLabel="1" />
        <Key
            android:codes="50"
            android:keyLabel="2" />
        <Key
            android:codes="51"
            android:keyLabel="3" />
    </Row>
    <Row>
        <Key
            android:codes="46"
            android:keyEdgeFlags="left"
            android:keyLabel="." />
        <Key
            android:codes="48"
            android:keyLabel="0" />
        <Key
            android:codes="-5"
            android:isRepeatable="true"
            android:keyIcon="@drawable/sym_keyboard_delete" />
    </Row>

</Keyboard>

布局文件,这边就只截图显示,反正大家自己看着搭建就是了:


calculator_dialog

CalculatorFinancialDialog.java:

利率计算方程式我就不贴了,毕竟影响不大

/**
 * Created by caihan on 2017/1/5.
 * 理财计算器(新版)
 */
public class CalculatorFinancialDialog extends Dialog
        implements View.OnClickListener, TextWatcher {
    Activity context;
    private Spinner spinner1;
    private ImageView spinner_performclick;
    private Window window = null;
    private SimpleAdapter simpleAdapter;
    private EditText investment_money;
    private EditText annual_rate;
    private EditText investment_mouth;
    private TextView product_expected_income;
    private TextView bank_expected_income;
    private Reimbursement type = Reimbursement.Dengebenxi;
    private String rate;
    private String mouth;
    private CustomKeyboard mCustomKeyboard;

    public CalculatorFinancialDialog(Activity context) {
        super(context, R.style.MyDialog);
        this.context = context;

    }

    public CalculatorFinancialDialog(Activity context, String rate,
                                     String mouth) {
        super(context, R.style.MyDialog);
        this.context = context;
        this.rate = rate;
        this.mouth = mouth;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.calculator_financial_dialog);
        this.setCanceledOnTouchOutside(false);
        mCustomKeyboard = new CustomKeyboard(this, R.id.keyboardview,
                R.xml.hexkbd);
        simpleAdapter = new SimpleAdapter(context, getData(),
                R.layout.items_spinner, new String[]
                {"TypeName"}, new int[]
                {R.id.textview});
        initWindowView();
        initView();
        initListener();
    }

    @SuppressWarnings("deprecation")
    private void initWindowView() {
        window = getWindow();
        window.setWindowAnimations(R.style.dialogWindowAnim);
        window.getDecorView().setPadding(0, 0, 0, 10);
        window.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.FILL_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        setCanceledOnTouchOutside(true);
        setCancelable(true);
    }

    private void initListener() {
        findViewById(R.id.calculator_dialog_false).setOnClickListener(this);
        spinner_performclick.setOnClickListener(this);
        spinner1.setAdapter(simpleAdapter);
        spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                switch (position) {
                    case 0:
                        type = Reimbursement.Dengebenxi;
                        break;
                    case 1:
                        type = Reimbursement.Daoqihuanbenhuanxi;
                        break;
                    case 2:
                        type = Reimbursement.Anyuefuxi;
                        break;
                    case 3:
                        type = Reimbursement.Anyuefuxidaoqihuanben;
                        break;
                    default:
                        type = Reimbursement.Dengebenxi;
                        break;
                }
                if (isCanPost()) {
                    product_expected_income
                            .setText(intercept(BorrowCalculateManagerImpl.Bill(
                                    DoubleUtils.toDouble(investment_money.getText().toString()),
                                    DoubleUtils.toDouble(investment_mouth.getText().toString()),
                                    DoubleUtils.toDouble(annual_rate.getText().toString()), type)));

                    bank_expected_income
                            .setText(intercept(BorrowCalculateManagerImpl.Bill(
                                    DoubleUtils.toDouble(investment_money
                                            .getText().toString()),
                                    DoubleUtils.toDouble(investment_mouth
                                            .getText().toString()),
                                    3.0, type)));
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        investment_money
                .addTextChangedListener(new MyTextListener("investment_money"));
        annual_rate.addTextChangedListener(new MyTextListener("annual_rate"));
        investment_mouth
                .addTextChangedListener(new MyTextListener("investment_mouth"));

    }

    private void initView() {
        spinner1 = (Spinner) findViewById(R.id.spinnerBase1);
        spinner_performclick = (ImageView) findViewById(R.id.spinner_performclick);
        investment_money = (EditText) findViewById(R.id.investment_money);
        annual_rate = (EditText) findViewById(R.id.annual_rate);
        investment_mouth = (EditText) findViewById(R.id.investment_mouth);
        product_expected_income = (TextView) findViewById(R.id.product_expected_income);
        bank_expected_income = (TextView) findViewById(R.id.bank_expected_income);
        annual_rate.addTextChangedListener(this);
        mCustomKeyboard.registerEditText(investment_money);
        mCustomKeyboard.registerEditText(annual_rate);
        mCustomKeyboard.registerEditText(investment_mouth);
        investment_mouth.setText(mouth);
        annual_rate.setText(rate);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.spinner_performclick:
                spinner1.performClick();
                break;
            case R.id.calculator_dialog_false:
                dismiss();
                break;

            default:
                break;
        }
    }

    public List<Map<String, Object>> getData() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("TypeName", "等额本息");
        list.add(map);
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("TypeName", "到期还本还息");
        list.add(map2);
        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("TypeName", "按月付息");
        list.add(map3);
        return list;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        TextWatcherUtil.getMoneyFormat(s.toString(), annual_rate);
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    class MyTextListener implements TextWatcher {
        private String inputEditView = null;

        public MyTextListener(String inputEditView) {
            this.inputEditView = inputEditView;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,int count) {
            if (s.toString().startsWith(".")
                    || s.toString().matches("[0]{1}[0-9]{1}")) {
                if ("investment_money".equals(inputEditView)) {
                    if (s.toString().matches("[0]{1}[0-9]{1}")) {
                        investment_money.setText("0");
                        investment_money.setSelection(1);
                    } else {
                        investment_money.setText("");
                    }
                    return;
                }
                if ("annual_rate".equals(inputEditView)) {
                    if (s.toString().matches("[0]{1}[0-9]{1}")) {
                        investment_money.setSelection(1);
                        annual_rate.setText("0");
                    } else {
                        annual_rate.setText("");
                    }

                    return;
                }
                if ("investment_mouth".equals(inputEditView)) {
                    if (s.toString().matches("[0]{1}[0-9]{1}")) {
                        investment_money.setSelection(1);
                        investment_mouth.setText("0");
                    } else {
                        investment_mouth.setText("");
                    }

                    return;
                }
            } else {
                if (isCanPost()) {
                    product_expected_income
                            .setText(intercept(BorrowCalculateManagerImpl.Bill(
                                    DoubleUtils.toDouble(investment_money
                                            .getText().toString()),
                                    DoubleUtils.toDouble(investment_mouth
                                            .getText().toString()),
                                    DoubleUtils.toDouble(
                                            annual_rate.getText().toString()),
                                    type)));

                    bank_expected_income
                            .setText(intercept(BorrowCalculateManagerImpl.Bill(
                                    DoubleUtils.toDouble(investment_money
                                            .getText().toString()),
                                    DoubleUtils.toDouble(investment_mouth
                                            .getText().toString()),
                                    3.0, type)));
                } else {
                    product_expected_income.setText("0");
                    bank_expected_income.setText("0");
                }

            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }

    }

    private String intercept(String account) {
        String number = StringUtils.getDoubleFormat(account);
        return number + "元";
    }

    public boolean isCanPost() {
        return (!StringUtils.isEmpty2(investment_money.getText().toString())
                && !StringUtils.isEmpty2(investment_mouth.getText().toString())
                && !StringUtils.isEmpty2(annual_rate.getText().toString()));
    }
}

CustomKeyboard.java

/**
 * Created by caihan on 2017/1/5.
 * 自定义键盘
 */
public class CustomKeyboard {

    private KeyboardView mKeyboardView;
    private Dialog mHostActivity;

    private OnKeyboardActionListener mOnKeyboardActionListener = new OnKeyboardActionListener() {

        public final static int CodeDelete = -5; // Keyboard.KEYCODE_DELETE
        public final static int CodeCancel = -3; // Keyboard.KEYCODE_CANCEL

        @Override
        public void onKey(int primaryCode, int[] keyCodes) {
            View focusCurrent = mHostActivity.getWindow().getCurrentFocus();
            if (focusCurrent == null ||
                    (focusCurrent.getClass() != EditText.class && focusCurrent.getClass() != AppCompatEditText.class)) {
                return;
            }
            EditText edittext = (EditText) focusCurrent;
            Editable editable = edittext.getText();
            int start = edittext.getSelectionStart();
            if (primaryCode == CodeCancel) {
                hideCustomKeyboard();
            } else if (primaryCode == CodeDelete) {
                if (editable != null && start > 0)
                    editable.delete(start - 1, start);
            } else {
                editable.insert(start, Character.toString((char) primaryCode));
            }
        }

        @Override
        public void onPress(int arg0) {
        }

        @Override
        public void onRelease(int primaryCode) {
        }

        @Override
        public void onText(CharSequence text) {
        }

        @Override
        public void swipeDown() {
        }

        @Override
        public void swipeLeft() {
        }

        @Override
        public void swipeRight() {
        }

        @Override
        public void swipeUp() {
        }
    };

    public CustomKeyboard(Dialog calculatorDialog, int viewid, int layoutid) {
        mHostActivity = calculatorDialog;
        mKeyboardView = (KeyboardView) calculatorDialog.findViewById(viewid);
        mKeyboardView.setKeyboard(
                new Keyboard(mHostActivity.getContext(), layoutid));
        mKeyboardView.setPreviewEnabled(false); // 显示白板
        mKeyboardView.setOnKeyboardActionListener(mOnKeyboardActionListener);
    }

    /**
     * 隐藏.
     */
    public void hideCustomKeyboard() {
        mKeyboardView.setVisibility(View.GONE);
        mKeyboardView.setEnabled(false);
    }

    public void registerEditText(int resid) {
        EditText edittext = (EditText) mHostActivity.findViewById(resid);
        edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
            }
        });
        edittext.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        edittext.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                EditText edittext = (EditText) v;
                int inType = edittext.getInputType();
                edittext.setInputType(InputType.TYPE_NULL);
                edittext.onTouchEvent(event);
                edittext.setInputType(inType);
                return true;
            }
        });
        edittext.setInputType(edittext.getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    }

    public void registerEditText(EditText edittext) {
        edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
            }
        });
        edittext.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        edittext.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                EditText edittext = (EditText) v;
                int inType = edittext.getInputType();
                edittext.setInputType(InputType.TYPE_NULL);
                edittext.onTouchEvent(event);
                edittext.setInputType(inType);
                return true;
            }
        });
        edittext.setInputType(edittext.getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    }

}