package com.sjkj.base_lib.utils;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;

import com.sjkj.base_lib.R;


/**
 * Created by Francis on 2017/12/20.
 * 保留指定位数的小数点
 */
public class KeepDecimalEditText extends AppCompatEditText {
    public boolean isInput = false;//是否是输入的
    ICallBack icallBack = null;
    public KeepDecimalEditText(@NonNull Context context) {
        super(context,null);
    }

    public KeepDecimalEditText(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.KeepDecimalEditText, 0, 0);
        typedArray.getIndexCount();
        typedArray.getIndex(0);
        int befor_integer = typedArray.getInteger(R.styleable.KeepDecimalEditText_befor_integer, 10);
        int decimal = typedArray.getInteger(R.styleable.KeepDecimalEditText_decimal, 3);
        setFilters(new InputFilter[]{new DecimalDigitsInputFilter(befor_integer,decimal)});
        initOnTouchListener();
        initTextChangedListener();
    }


    private void initTextChangedListener() {
        addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim().startsWith(".")) {
                    s = "0" + s;
                    setText(s);
                    setSelection(1);
                }
                if (icallBack != null  && isInput ) {
                    icallBack.onInputEditText(s.toString());
                }
            }

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

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    public interface ICallBack {
        void onInputEditText(String str);
    }

    public void setOnInputEditText(ICallBack iBack) {
        icallBack = iBack;
    }

    private void initOnTouchListener() {
        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                isInput = true;
                return false;
            }
        });
    }
}




